High-Performance ORM for ScyllaDB in Rust
Use monstrous tandem of scylla and charybdis for your next project
⚠️ WIP: This project is currently in an experimental stage; It uses async trait support from rust 1.75.0 beta release
Charybdis is a ORM layer on top of scylla_rust_driver focused on easy of use and performance
Usage considerations:
- Provide and expressive API for CRUD & Complex Query operations on model as a whole
- Provide easy way to work with subset of model fields by using automatically generated
partial_<model>!macro - Provide easy way to run complex queries by using automatically generated
find_<model>!macro - Automatic migration tool that analyzes the
src/model/*.rsfiles and runs migrations according to differences between the model definition and database
Performance consideration:
- It's build by beta release, so it uses builtin support for
async/awaitin traits that will be stabilized in Rust1.75 - It uses prepared statements (shard/token aware) -> bind values
- It expects
CachingSessionas a session arg for operations - Queries are macro generated str constants (no concatenation at runtime)
- By using
find_<model>!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
- Automatic migration with
charybdis-migrate - Basic Operations
- Partial Model Operations
- View Operations
- Callbacks
- Batch Operations
- As Native
- Collection queries
- Ignored fields
- Roadmap
Charybdis Models
Define Tables
Declare model as a struct within src/models dir:
// src/modles/user.rs
use charybdis_model;
use ;
(Note we use src/models as automatic migration tool expects that dir)
Define UDT
Declare udt model as a struct within src/models/udts dir:
// src/models/udts/address.rs
use charybdis_udt_model;
use Text;
Define Materialized Views
Declare view model as a struct within src/models/materialized_views dir:
// src/models/materialized_views/users_by_username.rs
use charybdis_view_model;
use ;
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)
📝 Primary key fields should not be wrapped in Option<> as they are mandatory.
Automatic migration
charybdis-migrate tool that enables automatic migration to database without need to write migrations by hand.
It expects src/models files and generates migrations based on differences between model definitions and database.
It supports following operations:
- Create new tables
- Create new columns
- Drop columns
- Create secondary indexes
- Drop secondary indexes
- Create UDTs (
src/models/udts) - Create materialized views (
src/models/materialized_views) - Table options
⚠️ If table exists, table options will result in alter table query that withoutCLUSTERING ORDERandCOMPACT STORAGEoptions.
🟢 Tables, Types and UDT dropping is not added. If you don't define model within src/model dir
it will leave db structure as it is.
⚠️ 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.
Global secondary indexes
They are simply defined as array of strings:
Local secondary Indexes
They are defined as array of tuples
- first element is array of partition keys
- second element is array of clustering keys
)]
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.
Create
use ;
async
Find
Find by primary key
This is preferred way to query data rather then
find_by_primary_key_val associated fun, as it will automatically provide correct order
based on primary key definition.
let user = User ;
let user = user.find_by_primary_key.await?;
Find by partition key
let users = User .find_by_partition_key.await;
Macro generated find helpers
Lets say we have model:
We have macro generated functions for up to 3 fields from primary key.
find_by_date
🟢 Note that if complete primary key is provided, we get single typed result. So for our user
model we get find_by_id function that returns Result<User, CharybdisError>.
Custom filtering:
Let's say we have a model:
We get automatically generated find_post! macro that follows convention find_<struct_name>!.
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 res = find_post!.await?;
We can also use find_first_post! macro to get single result:
let post = find_first_post!
If we just need the Query and not the result, we can use find_post_query! macro:
let query = find_post_query!
Update
let user = from_json;
user.username = "scylla".to_string;
user.email = "some@email.com";
user.update.await;
Delete
let user = from_json;
user.delete.await;
Macro generated delete helpers
Lets say we have model:
We have macro generated functions for up to 3 fields from primary key.
delete_by_date;
delete_by_date_and_category_id;
delete_by_date_and_category_id_and_title;
Partial Model Operations:
Use auto generated partial_<model>! macro to run operations on subset of the model fields.
This macro generates a new struct with same structure as the original model, but only with provided fields.
Macro is automatically generated by #[charybdis_model].
It follows convention partial_<struct_name>!.
// auto-generated macro - available in crate::models::user
partial_user!;
let id = new_v4;
let user = UpdateUsernameUser ;
// we can have same operations as on base model
// INSERT into users (id, username) VALUES (?, ?)
user.insert.await;
// UPDATE users SET username = ? WHERE id = ?
user.update.await;
// DELETE FROM users WHERE id = ?
user.delete.await;
// get partial PartUser
let partial_user = user.find_by_primary_key.await?;
// get native user model by primary key
let user = user.as_native.find_by_primary_key.await?;
Partial Model Considerations:
-
partial_<model>require complete primary key in definition -
All derives that are defined bellow
#charybdis_modelmacro will be automatically added to partial model. -
partial_<model>struct implements same field attributes as original model, so if we have#[serde(rename = "rootId")]on original model field, it will be present on partial model field.
Recommended naming convention is Purpose + Original Struct Name. E.g:
UpdateAdresssUser, UpdateDescriptionPost.
Callbacks
We can define callbacks that will be executed before and after certain operations.
Note that callbacks returns custom error class that implements From<CharybdisError>.
use *;
Possible callbacks:
before_insertafter_insertbefore_updateafter_updatebefore_deleteafter_delete
⚠️ In order to trigger callback, instead of calling insert method on model, we can call
insert_cb. This enables us to have clear distinction between insert and insert with callbacks.
let post = from_json;
let res = post.insert_cb.await;
match res
ExtensionCallbacks
We can also define callbacks that will be given custom extension if needed.
Let's say we define custom extension that will be used to update elastic document on every post update:
We can define after_update callback on Post
that has custom extension as type:
So to trigger callback we use same update_cb method:
let post = from_json;
let res = post.update_cb.await;
Note that CustomError has to implement From<CharybdisError>.
Batch Operations
For batched operations we can make use of CharybdisModelBatch.
let mut batch = new;
let users: = Vecfrom_json;
// inserts
batch.append_inserts;
// or updates
batch.append_updates;
// or deletes
batch.append_deletes;
batch.execute.await;
It also supports chunked batch operations
chunk_size = 100;
chunked_inserts.await?;
As Native
In case we need to run operations on native model, we can use as_native method:
partial_user!;
let mut update_user_username = UpdateUser ;
let native_user: User = update_user_username.as_native.find_by_primary_key.await?;
// action that requires native model
authorize_user;
as_native works by returning new instance of native model with fields from partial model.
For other fields it uses default values.
Collections
For every field that is defined with List<T> type or Set<T>, we get following:
PUSH_<field_name>_QUERYstatic strPULL_<field_name>_QUERYstatic strpush_<field_name>methodpull_<field_name>method
let query = PUSH_TAGS_QUERY;
execute.await;
let query = PULL_POST_IDS_QUERY;
execute.await;
Methods take session and value as arguments:
let user = from_json;
user.push_tags.await;
user.pull_post_ids.await;
Ignored fields
We can ignore fields by using #[charybdis(ignore)] attribute:
So field organization will be ignored in all operations and
default value will be used when deserializing from other data sources.
It can be used to hold data that is not persisted in database.
Roadmap:
- Add tests
- Write
modelizecommand to generatesrc/models/*structs from existing database - Add --drop flag to migrate command to drop tables, types and UDTs if they are not defined in
src/models