### Installing charybdis-migrate Tool (Bash) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis-migrate/README.md This command installs the `charybdis-migrate` command-line tool, which is used for automatic database migrations. It's a prerequisite for using the migration features. ```bash cargo install charybdis-migrate ``` -------------------------------- ### Running Charybdis Database Migrations (Bash) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This Bash snippet provides commands to install the `charybdis-migrate` CLI tool and execute database migrations. It highlights the use of `--hosts` and `--keyspace` flags for connection details, and the optional `--drop-and-replace` flag for column type changes. ```Bash cargo install charybdis-migrate migrate --hosts --keyspace --drop-and-replace (optional) ``` -------------------------------- ### Executing Charybdis Collection Updates in a Batch (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This example demonstrates how to use the generated static collection queries within a batch operation. It shows how to create a batch, append statements for updating user tags, and then execute the batch asynchronously against the database session for efficient bulk operations. ```Rust let batch = User::batch(); let users: Vec; for user in users { batch.append_statement(User::PUSH_TAGS_QUERY, (vec![tag], user.id)); } batch.execute(&session).await; ``` -------------------------------- ### Running Charybdis Migration from CLI Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This Bash snippet provides commands to install and execute the `charybdis-migrate` command-line tool. It shows how to specify database hosts, keyspace, and optionally use the `--drop-and-replace` flag for altering column types, enabling automatic database schema migration based on model definitions. ```Bash cargo install charybdis-migrate migrate --hosts --keyspace --drop-and-replace (optional) ``` -------------------------------- ### Performing Chunked Batch Operations in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This example illustrates how to handle large amounts of data by performing batch operations in chunks. It uses `chunked_inserts`, `chunked_updates`, and `chunked_deletes` methods, specifying a `chunk_size` to process data efficiently. ```Rust let users: Vec; let chunk_size = 100; User::batch().chunked_inserts(&session, users, chunk_size).await?; User::batch().chunked_updates(&session, users, chunk_size).await?; User::batch().chunked_deletes(&session, users, chunk_size).await?; ``` -------------------------------- ### Exploring Charybdis Find Functions for Post Model (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This comprehensive example showcases various automatically generated 'find' functions for a 'Post' model in Charybdis. It demonstrates querying by partition keys, clustering keys, local secondary indexes, and global secondary indexes, illustrating how to retrieve streams of models, single models, or optional models based on the query type. It requires a 'CachingSession' for database operations. ```rust use scylla::client::caching_session::CachingSession; use charybdis::errors::CharybdisError; use charybdis::macros::charybdis_model; use charybdis::stream::CharybdisModelStream; use charybdis::types::{Date, Text, Uuid}; #[charybdis_model( table_name = posts, partition_keys = [date], clustering_keys = [category_id, title], global_secondary_indexes = [category_id], local_secondary_indexes = [title] )] pub struct Post { pub date: Date, pub category_id: Uuid, pub title: Text, } impl Post { async fn find_various(db_session: &CachingSession) -> Result<(), CharybdisError> { let date = Date::default(); let category_id = Uuid::new_v4(); let title = Text::default(); let posts: CharybdisModelStream = Post::find_by_date(date).execute(db_session).await?; let posts: CharybdisModelStream = Post::find_by_date_and_category_id(date, category_id).execute(db_session).await?; let posts: Post = Post::find_by_date_and_category_id_and_title(date, category_id, title.clone()).execute(db_session).await?; let post: Post = Post::find_first_by_date(date).execute(db_session).await?; let post: Post = Post::find_first_by_date_and_category_id(date, category_id).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date(date).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date_and_category_id(date, category_id).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date_and_category_id_and_title(date, category_id, title.clone()).execute(db_session).await?; // find by local secondary index let posts: CharybdisModelStream = Post::find_by_date_and_title(date, title.clone()).execute(db_session).await?; let post: Post = Post::find_first_by_date_and_title(date, title.clone()).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date_and_title(date, title.clone()).execute(db_session).await?; // find by global secondary index let posts: CharybdisModelStream = Post::find_by_category_id(category_id).execute(db_session).await?; let post: Post = Post::find_first_by_category_id(category_id).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_category_id(category_id).execute(db_session).await?; Ok(()) } } ``` -------------------------------- ### Executing Batch Operations with Generated Charybdis Queries - Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This Rust example demonstrates how to use the generated static query constants, such as `User::PUSH_TAGS_QUERY`, within Charybdis batch operations. It shows appending multiple update statements to a batch for efficiency and then executing the batch asynchronously against a session. ```Rust let batch = User::batch(); let users: Vec; for user in users { batch.append_statement(User::PUSH_TAGS_QUERY, (vec![tag], user.id)); } batch.execute(&session).await; ``` -------------------------------- ### Finding Data by Primary Key in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This example illustrates how to retrieve a single record from the database by its primary key using Charybdis. It initializes a 'User' struct with only the 'id' (primary key) and then calls 'find_by_primary_key().execute()' to fetch the corresponding user. A 'CachingSession' is required for database interaction. ```rust let user = User {id, ..Default::default()}; let user = user.find_by_primary_key().execute(&session).await?; ``` -------------------------------- ### Defining Custom Application Extensions in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet defines a custom `AppExtensions` struct, which serves as a container for application-wide dependencies. In this example, it holds an `ElasticClient` instance, enabling integration with Elasticsearch for operations like updating documents based on database changes. ```Rust pub struct AppExtensions { pub elastic_client: ElasticClient, } ``` -------------------------------- ### Appending Operations to Configured Batch in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This example demonstrates how to append individual update operations to a batch that has already been configured with specific consistency and retry policies. It shows chaining `append_update` calls before executing the batch. ```Rust let batch = User::batch() .consistency(Consistency::One) .retry_policy(Some(Arc::new(DefaultRetryPolicy::new()))) .append_update(&user_1) .append_update(&user_2) .execute(data.db_session()) .await?; ``` -------------------------------- ### Defining User Model with Collection Fields - Charybdis Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet defines the `User` struct using the `charybdis_model` macro, specifying `users` as the table name and `id` as the partition key. It includes examples of collection types like `Set` for `tags` and `List` for `post_ids`, which are supported by Charybdis. ```Rust #[charybdis_model( table_name = users, partition_keys = [id], clustering_keys = [], )] pub struct User { id: Uuid, tags: Set, post_ids: List, } ``` -------------------------------- ### Updating Model Fields Using a Partial Model in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This example shows how to instantiate and use a partial model struct (`UpdateUsernameUser`) to perform an update operation on only the specified fields (`username`) of the original model. It highlights the efficiency of updating only necessary fields. ```Rust let mut update_user_username = UpdateUsernameUser { id, username: "updated_username".to_string(), }; update_user_username.update().execute(&session).await?; ``` -------------------------------- ### Auto-generated Materialized View Query (SQL) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This SQL snippet shows an example of a `CREATE MATERIALIZED VIEW` statement that Charybdis automatically generates based on a Rust model definition. It specifies the view name, selected columns, base table, `WHERE` clause for non-null values, and the `PRIMARY KEY` for the materialized view. ```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) ``` -------------------------------- ### Custom Filtering with find_first_post! Macro in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This example shows how to use the 'find_first_post!' macro in Charybdis to retrieve a single 'Post' result from a custom query. It constructs a query to find the first 'Post' where 'category_id' is in a vector and 'date' is greater than a specified value, with a 'LIMIT 1' clause. A 'CachingSession' is needed for execution. ```rust let post = find_first_post!("category_id in ? AND date > ? LIMIT 1", (date, categor_vec)) .execute(session) .await?; ``` -------------------------------- ### Ignoring Fields in Charybdis Models (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This example demonstrates how to use the `#[charybdis(ignore)]` attribute to exclude a field, such as `organization`, from all database operations. This allows the field to hold data that is not persisted in the database or to use default values when deserializing from other data sources. ```Rust #[charybdis_model(...)] pub struct User { id: Uuid, #[charybdis(ignore)] organization: Option, } ``` -------------------------------- ### Using charybdis-migrate Tool (Bash) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis-migrate/README.md This command executes the `charybdis-migrate` tool to perform database migrations. It requires specifying the database host(s) and keyspace, with an optional flag to drop and recreate columns for type changes. ```bash migrate --hosts --keyspace --drop-and-replace (optional) ``` -------------------------------- ### Programmatically Running Charybdis Migrations (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This Rust snippet demonstrates how to programmatically trigger database migrations within an application, typically for testing or development environments. It uses `MigrationBuilder` to configure the keyspace and `drop_and_replace` option, then builds and runs the migration against a Charybdis session. ```Rust use charybdis::migrate::MigrationBuilder; let migration = MigrationBuilder::new() .keyspace("test") .drop_and_replace(true) .build(&session) .await; migration.run().await; ``` -------------------------------- ### Demonstrating Various Find Functions with Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This comprehensive snippet showcases a variety of automatically generated `find` functions for a `Post` model, including queries by partition keys, clustering keys, local secondary indexes, and global secondary indexes. It covers methods to retrieve streams of models, single models, and optional single models, illustrating the flexibility of Charybdis's query API. ```Rust use scylla::client::caching_session::CachingSession; use charybdis::errors::CharybdisError; use charybdis::macros::charybdis_model; use charybdis::stream::CharybdisModelStream; use charybdis::types::{Date, Text, Uuid}; #[charybdis_model( table_name = posts, partition_keys = [date], clustering_keys = [category_id, title], global_secondary_indexes = [category_id], local_secondary_indexes = [title] )] pub struct Post { pub date: Date, pub category_id: Uuid, pub title: Text, } impl Post { async fn find_various(db_session: &CachingSession) -> Result<(), CharybdisError> { let date = Date::default(); let category_id = Uuid::new_v4(); let title = Text::default(); let posts: CharybdisModelStream = Post::find_by_date(date).execute(db_session).await?; let posts: CharybdisModelStream = Post::find_by_date_and_category_id(date, category_id).execute(db_session).await?; let posts: Post = Post::find_by_date_and_category_id_and_title(date, category_id, title.clone()).execute(db_session).await?; let post: Post = Post::find_first_by_date(date).execute(db_session).await?; let post: Post = Post::find_first_by_date_and_category_id(date, category_id).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date(date).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date_and_category_id(date, category_id).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date_and_category_id_and_title(date, category_id, title.clone()).execute(db_session).await?; // find by local secondary index let posts: CharybdisModelStream = Post::find_by_date_and_title(date, title.clone()).execute(db_session).await?; let post: Post = Post::find_first_by_date_and_title(date, title.clone()).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_date_and_title(date, title.clone()).execute(db_session).await?; // find by global secondary index let posts: CharybdisModelStream = Post::find_by_category_id(category_id).execute(db_session).await?; let post: Post = Post::find_first_by_category_id(category_id).execute(db_session).await?; let post: Option = Post::maybe_find_first_by_category_id(category_id).execute(db_session).await?; Ok(()) } } ``` -------------------------------- ### Programmatically Running Charybdis Migrations in Rust Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This Rust snippet demonstrates how to programmatically trigger database migrations within a Rust application, typically for testing or development environments. It uses `MigrationBuilder` to configure the keyspace and `drop_and_replace` option, then builds and runs the migration against an existing session. ```Rust use charybdis::migrate::MigrationBuilder; let migration = MigrationBuilder::new() .keyspace("test") .drop_and_replace(true) .build(&session) .await; migration.run().await; ``` -------------------------------- ### Adding Charybdis and ScyllaDB Dependencies (TOML) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This TOML snippet demonstrates how to include the `scylla` and `charybdis` crates as dependencies in your `Cargo.toml` file. It is critical to ensure that the version of `scylla` specified matches the version used internally by the `charybdis` crate to avoid compatibility issues. ```TOML [dependencies] scylla = "1.1.0" charybdis = "1.0.1" ``` -------------------------------- ### Performing Basic Batch Operations in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates how to perform basic batch operations (inserts, updates, deletes) using `CharybdisModelBatch`. It shows how to append collections of `User` objects for different types of operations and then execute the batch against a session. This allows for efficient execution of multiple DML statements. ```Rust let users: Vec; let batch = User::batch(); // inserts batch.append_inserts(users); // or updates batch.append_updates(users); // or deletes batch.append_deletes(users); batch.execute(&session).await?; ``` -------------------------------- ### Adding Charybdis and ScyllaDB Dependencies Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This TOML snippet demonstrates how to include the necessary `scylla` and `charybdis` crates in your `Cargo.toml` file, specifying their versions. These dependencies are fundamental for using the Charybdis ORM in a Rust project. ```TOML [dependencies] scylla = "1.1.0" charybdis = "1.0.1" ``` -------------------------------- ### Updating Fields Using a Generated Partial Model (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates how to instantiate and use a partial model (e.g., `UpdateUsernameUser`) generated by the `partial_!` macro. It shows setting values for the partial model's fields and then executing an update operation, which efficiently updates only the specified fields in the database. ```Rust let mut update_user_username = UpdateUsernameUser { id, username: "updated_username".to_string(), }; update_user_username.update().execute(&session).await?; ``` -------------------------------- ### Configuring Batch Operations with Chaining in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates configuring batch operations using method chaining before execution. It shows how to set `consistency` and `retry_policy` for a batch, then perform `chunked_inserts`. This allows fine-grained control over batch behavior, such as data consistency and error handling. ```Rust let batch = User::batch() .consistency(Consistency::One) .retry_policy(Some(Arc::new(DefaultRetryPolicy::new()))) .chunked_inserts(&session, users, 100) .await?; ``` -------------------------------- ### Configuring Batch Operations with Method Chaining in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet shows how to configure batch operations using method chaining before execution. It demonstrates setting the `consistency` level and a `retry_policy` for a chunked insert operation. ```Rust let batch = User::batch() .consistency(Consistency::One) .retry_policy(Some(Arc::new(DefaultRetryPolicy::new()))) .chunked_inserts(&session, users, 100) .await?; ``` -------------------------------- ### Finding Data by Partition Key in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet demonstrates how to query for records based on their partition key using Charybdis. It initializes a 'User' struct with the partition key 'id' and then uses 'find_by_partition_key().execute()' to retrieve all users belonging to that partition. A 'CachingSession' is necessary for database operations. ```rust let users = User {id, ..Default::default()}.find_by_partition_key().execute(&session).await; ``` -------------------------------- ### Converting Partial Model to Native Model with `as_native` (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet illustrates the use of the `as_native` method to convert a partial model instance back into a native model instance. This is useful when an operation or function requires the full native model, allowing partial models to be used for focused updates and then converted for broader operations. ```Rust let native_user: User = update_user_username.as_native().find_by_primary_key().execute(&session).await?; // action that requires native model authorize_user(&native_user); ``` -------------------------------- ### Finding Data by Partition Key in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet illustrates how to query for records using only the partition key. It initializes a `User` struct with the `id` (assuming `id` is part of the partition key) and then uses `find_by_partition_key().execute()` to retrieve potentially multiple records that share the same partition key. ```Rust let users = User {id, ..Default::default()}.find_by_partition_key().execute(&session).await; ``` -------------------------------- ### Configuring Charybdis Queries with Method Chaining (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This code demonstrates how to configure `CharybdisQuery` objects using method chaining before execution. It shows setting query options like `consistency` (e.g., `Consistency::One`) and `timeout` for both `find_by_id` and `update` operations, allowing fine-grained control over query behavior. ```rust let user: User = User::find_by_id(id) .consistency(Consistency::One) .timeout(Some(Duration::from_secs(5))) .execute(&app.session) .await?; let result: QueryResult = user.update().consistency(Consistency::One).execute(&session).await?; ``` -------------------------------- ### Creating Custom Delete Queries with `delete_post!` Macro (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet illustrates how to construct custom delete queries using the `delete_post!` macro in Charybdis. It allows for more flexible deletion conditions, such as deleting posts where the `date` matches and `category_id` is within a specified list, by providing a raw CQL-like string and corresponding parameters. ```rust delete_post!("date = ? AND category_id in ?", (date, category_vec)).execute(&session).await? ``` -------------------------------- ### Converting Partial Model to Native Model in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet illustrates how to use the `as_native` method to convert a partial model instance (`update_user_username`) back into a full native model (`User`). This allows performing operations that require the complete model, with other fields defaulting. ```Rust let native_user: User = update_user_username.as_native().find_by_primary_key().execute(&session).await?; // action that requires native model authorize_user(&native_user); ``` -------------------------------- ### Configuring Table Options for Charybdis Model (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This Rust code demonstrates how to apply custom table options to a Charybdis model using the `table_options` attribute within the `charybdis_model` macro. It allows specifying Cassandra/ScyllaDB-specific options like `CLUSTERING ORDER BY` and `gc_grace_seconds` directly in the model definition. ```Rust #[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 {...} ``` -------------------------------- ### Configuring Charybdis Queries with Method Chaining - Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates how to configure Charybdis queries using method chaining before execution. It shows setting consistency levels and timeouts for both `find_by_id` and `update` operations, allowing fine-grained control over query behavior and performance. ```Rust let user: User = User::find_by_id(id) .consistency(Consistency::One) .timeout(Some(Duration::from_secs(5))) .execute(&app.session) .await?; let result: QueryResult = user.update().consistency(Consistency::One).execute(&session).await?; ``` -------------------------------- ### Finding Data by Primary Key in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet shows how to retrieve a single `User` record from the database by its primary key. It initializes a `User` struct with only the `id` (primary key) and then calls `find_by_primary_key().execute()` to fetch the corresponding record. ```Rust let user = User {id, ..Default::default()}; let user = user.find_by_primary_key().execute(&session).await?; ``` -------------------------------- ### Inserting Data with Charybdis in Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates how to insert a new `User` object into the database using the Charybdis ORM. It initializes a `User` struct with various fields, including an optional `Address` struct, and then uses the `insert().execute()` method to persist the data. Requires an initialized `CachingSession`. ```Rust use charybdis::{CachingSession, Insert}; #[tokio::main] async fn main() { let session: &CachingSession; // init sylla session // init user let user: User = User { id, email: "charybdis@nodecosmos.com".to_string(), username: "charybdis".to_string(), created_at: Utc::now(), updated_at: Utc::now(), address: Some( Address { street: "street".to_string(), state: "state".to_string(), zip: "zip".to_string(), country: "country".to_string(), city: "city".to_string(), } ), }; // create user.insert().execute(&session).await; } ``` -------------------------------- ### Appending Operations with Chained Configuration in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet shows how to configure a batch with method chaining (setting consistency and retry policy) and then append individual update operations using `append_update`. This approach is useful for building a batch with specific configurations and then adding operations one by one before execution. ```Rust let batch = User::batch() .consistency(Consistency::One) .retry_policy(Some(Arc::new(DefaultRetryPolicy::new()))) .append_update(&user_1) .append_update(&user_2) .execute(data.db_session()) .await?; ``` -------------------------------- ### Performing Basic Batch Operations in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet demonstrates how to use `CharybdisModelBatch` to perform multiple inserts, updates, or deletes on a collection of `User` objects in a single batch. It shows the `append_inserts`, `append_updates`, and `append_deletes` methods, followed by batch execution. ```Rust let users: Vec; let batch = User::batch(); // inserts batch.append_inserts(users); // or updates batch.append_updates(users); // or deletes batch.append_deletes(users); batch.execute(&session).await?; ``` -------------------------------- ### Defining Charybdis Model with Local Secondary Index (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis-migrate/README.md This Rust code defines a `menus` model with a local secondary index on the `dish_type` field, scoped to the `location` partition key. The migration tool will generate `CREATE INDEX ON menus((location), dish_type);`. ```rust #[charybdis_model( table_name = menus, partition_keys = [location], clustering_keys = [name, price, dish_type], global_secondary_indexes = [], local_secondary_indexes = [dish_type] )] ``` -------------------------------- ### Defining Charybdis Table Model (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis-migrate/README.md This Rust code defines a `User` struct as a Charybdis model, mapping it to a Cassandra table named `users`. It specifies partition keys, clustering keys, global secondary indexes, and includes various data types and a nested UDT (`Address`). ```rust 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 = [], )] pub struct User { pub id: Uuid, pub username: Text, pub email: Text, pub created_at: Timestamp, pub updated_at: Timestamp, pub address: Address, } ``` -------------------------------- ### Defining a Charybdis Model with Collection Fields (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet demonstrates how to define a `User` model using the `#[charybdis_model]` macro, showcasing various collection types like `Set`, `List`, and `Map>>` for mapping to Cassandra/ScyllaDB collection columns. It specifies `id` as a partition key. ```Rust #[charybdis_model( table_name = users, partition_keys = [id], clustering_keys = [] )] pub struct User { id: Uuid, tags: Set, post_ids: List, books_by_genre: Map>>, } ``` -------------------------------- ### Implementing Charybdis Callback Trait for Post Model (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This code implements the `Callback` trait for the `Post` model, demonstrating how to hook into various lifecycle events (before/after insert, update, delete). It utilizes the `AppExtensions` to interact with an `elastic_client` for updating and deleting Elastic documents, and sets default values for `id`, `created_at`, and `updated_at`. ```Rust #[charybdis_model(...)] pub struct Post {} impl Callback for Post { type Extention = AppExtensions; type Error = AppError; // From // use before_insert to set default values async fn before_insert( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { self.id = Uuid::new_v4(); self.created_at = Utc::now(); Ok(()) } // use before_update to set updated_at async fn before_update( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { self.updated_at = Utc::now(); Ok(()) } // use after_update to update elastic document async fn after_update( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { extension.elastic_client.update(...).await?; Ok(()) } // use after_delete to delete elastic document async fn after_delete( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { extension.elastic_client.delete(...).await?; Ok(()) } } ``` -------------------------------- ### Using Macro Generated Delete Helpers - Charybdis Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates the use of macro-generated delete helper functions provided by Charybdis for models with composite primary keys. These static methods allow deleting records by specifying a subset of the primary key fields, up to three, simplifying common delete operations. ```Rust Post::delete_by_date(date: Date).execute(&session).await?; Post::delete_by_date_and_category_id(date: Date, category_id: Uuid).execute(&session).await?; Post::delete_by_date_and_category_id_and_title(date: Date, category_id: Uuid, title: Text).execute(&session).await?; ``` -------------------------------- ### Finding Data by Primary Key Value in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This code shows an alternative method to find a record by its primary key in Charybdis. Instead of initializing a model instance, it directly uses the static method 'find_by_primary_key_value()' with the primary key value to fetch the desired user. A 'CachingSession' is required for database interaction. ```rust let users = User::find_by_primary_key_value(val: User::PrimaryKey).execute(&session).await; ``` -------------------------------- ### Defining Charybdis Model with Global Secondary Index (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis-migrate/README.md This Rust code defines a `users` model with a global secondary index on the `username` field. The `charybdis-migrate` tool will generate a `CREATE INDEX ON users (username);` query for this definition. ```rust #[charybdis_model( table_name = users, partition_keys = [id], clustering_keys = [], global_secondary_indexes = [username] )] ``` -------------------------------- ### Creating Custom Delete Queries with Macro - Charybdis Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet illustrates how to construct custom delete queries using the `delete_post!` macro in Charybdis. It allows for flexible deletion conditions, such as deleting posts where the `date` matches a value and `category_id` is within a specified list, providing more granular control over delete operations. ```Rust delete_post!("date = ? AND category_id in ?", (date, category_vec)).execute(&session).await? ``` -------------------------------- ### Implementing Charybdis Callback Trait for Post Model (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This Rust snippet demonstrates implementing the `Callback` trait for a `Post` model in Charybdis. It defines asynchronous hooks (`before_insert`, `before_update`, `after_update`, `after_delete`) that execute before or after database operations, allowing for tasks like setting default UUIDs and timestamps, or synchronizing data with an `ElasticClient` provided via `AppExtensions`. ```Rust #[charybdis_model(...)] pub struct Post {} impl Callback for Post { type Extention = AppExtensions; type Error = AppError; // From // use before_insert to set default values async fn before_insert( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { self.id = Uuid::new_v4(); self.created_at = Utc::now(); Ok(()) } // use before_update to set updated_at async fn before_update( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { self.updated_at = Utc::now(); Ok(()) } // use after_update to update elastic document async fn after_update( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { extension.elastic_client.update(...).await?; Ok(()) } // use after_delete to delete elastic document async fn after_delete( &mut self, _session: &CachingSession, extension: &AppExtensions, ) -> Result<(), CustomError> { extension.elastic_client.delete(...).await?; Ok(()) } } ``` -------------------------------- ### Custom Filtering with `find_post!` Macro in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates how to use the `find_post!` macro for custom queries, allowing for flexible filtering conditions. It constructs a query at compile time to return a stream of `Post` models based on `category_id` and `date` conditions. ```Rust // automatically generated macro rule let posts = find_post!("category_id in ? AND date > ?", (categor_vec, date)) .execute(session) .await?; ``` -------------------------------- ### Defining Table Options for Charybdis Model in Rust Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This Rust snippet demonstrates how to apply custom table options, such as `CLUSTERING ORDER BY` and `gc_grace_seconds`, to a Charybdis model using the `table_options` attribute within the `charybdis_model` macro. These options are directly passed as a raw string to the underlying Cassandra/ScyllaDB table definition. ```Rust #[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 {...} ``` -------------------------------- ### Defining Custom Application Extensions in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet defines the `AppExtensions` struct, which serves as a container for application-wide dependencies, such as an `ElasticClient`. It allows these dependencies to be passed to and utilized within Charybdis callbacks for integrating with external services. ```Rust pub struct AppExtensions { pub elastic_client: ElasticClient, } ``` -------------------------------- ### Triggering Charybdis Callbacks for Model Operations (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet demonstrates how to explicitly trigger callbacks for `insert`, `update`, and `delete` operations using the `_cb` methods provided by `charybdis::operations`. It shows how to pass the `app_extensions` and execute the operation, optionally configuring consistency levels for delete operations. ```Rust use charybdis::operations::{DeleteWithCallbacks, InsertWithCallbacks, UpdateWithCallbacks}; post.insert_cb(app_extensions).execute(&session).await; post.update_cb(app_extensions).execute(&session).await; post.delete_cb(app_extensions).consistency(Consistency::All).execute(&session).await; ``` -------------------------------- ### Defining a Charybdis Model for Macro-Generated Deletes (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet defines a `Post` struct using the `charybdis_model` macro, mapping it to the `posts` table. It highlights the definition of partition and clustering keys (`date`, `category_id`, `title`), which are crucial for Charybdis to generate helper delete functions based on these primary key components. ```rust #[charybdis_model( table_name = posts, partition_keys = [date], clustering_keys = [categogry_id, title], global_secondary_indexes = []) ] pub struct Post { date: Date, category_id: Uuid, title: Text, id: Uuid, ... } ``` -------------------------------- ### Inserting Data with Charybdis in Rust Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet demonstrates how to insert a new 'User' object into ScyllaDB using the Charybdis ORM. It initializes a 'User' struct with various fields, including an optional 'Address' struct, and then uses the 'insert().execute()' method to persist the data asynchronously. A 'CachingSession' is required to interact with the database. ```rust use charybdis::{CachingSession, Insert}; #[tokio::main] async fn main() { let session: &CachingSession; // init sylla session // init user let user: User = User { id, email: "charybdis@nodecosmos.com".to_string(), username: "charybdis".to_string(), created_at: Utc::now(), updated_at: Utc::now(), address: Some( Address { street: "street".to_string(), state: "state".to_string(), zip: "zip".to_string(), country: "country".to_string(), city: "city".to_string(), } ), }; // create user.insert().execute(&session).await; } ``` -------------------------------- ### Defining Charybdis Model with Table Options (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis-migrate/README.md This Rust code defines a `Commit` model using the `charybdis_model` macro, specifying table name, partition keys, clustering keys, and custom Cassandra table options like `CLUSTERING ORDER BY` and `gc_grace_seconds`. Note that `CLUSTERING ORDER` and `COMPACT STORAGE` options are not applied on existing tables during alter operations. ```rust #[charybdis_model( table_name = commits, partition_keys = [object_id], clustering_keys = [created_at, id], table_options = r#" CLUSTERING ORDER BY (created_at DESC) AND gc_grace_seconds = 86400 "# )] #[derive(Serialize, Deserialize, Default)] pub struct Commit {...} ``` -------------------------------- ### Using Macro-Generated Delete Functions by Primary Key (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This code demonstrates the use of Charybdis's macro-generated delete helper functions. These functions allow deleting `Post` records by specifying combinations of primary key fields (`date`, `category_id`, `title`), providing convenient ways to target specific rows for deletion without writing full queries. ```rust Post::delete_by_date(date: Date).execute(&session).await?; Post::delete_by_date_and_category_id(date: Date, category_id: Uuid).execute(&session).await?; Post::delete_by_date_and_category_id_and_title(date: Date, category_id: Uuid, title: Text).execute(&session).await?; ``` -------------------------------- ### Generating Query Statement with `find_post_query!` Macro (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet shows how to use the `find_post_query!` macro to obtain only the `Statement` object for a custom query, without executing it immediately. This is useful when the query needs to be prepared or used in a different context. ```Rust let query = find_post_query!("date = ? AND category_id in ?", (date, categor_vec)); ``` -------------------------------- ### Defining Post Model for Macro Generated Delete Helpers - Charybdis Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet defines the `Post` struct using the `charybdis_model` macro, specifying `posts` as the table name and a composite primary key consisting of `date` (partition key) and `category_id`, `title` (clustering keys). This structure enables Charybdis to generate specific delete helper methods. ```Rust #[charybdis_model( table_name = posts, partition_keys = [date], clustering_keys = [categogry_id, title], global_secondary_indexes = []) ] pub struct Post { date: Date, category_id: Uuid, title: Text, id: Uuid, ... } ``` -------------------------------- ### Performing Collection Operations with Statement Batching in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This snippet demonstrates using statement batching to perform collection operations. It iterates through a list of users and appends a custom statement (`User::PUSH_TAGS_QUERY`) for each, along with its parameters. This allows for batching custom DML operations that might not fit the standard `append_inserts`/`updates`/`deletes` patterns. ```Rust let batch = User::batch(); let users: Vec; for user in users { batch.append_statement(User::PUSH_TAGS_QUERY, (vec![tag], user.id)); } batch.execute(&session).await; ``` -------------------------------- ### Defining a Charybdis Model with Collection Fields (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis/README.md This snippet defines a `User` struct using the `charybdis_model` macro, mapping it to the `users` table. It showcases the use of `Set` for `tags` and `List` for `post_ids`, demonstrating how Charybdis handles collection types in model definitions. ```rust #[charybdis_model( table_name = users, partition_keys = [id], clustering_keys = [], )] pub struct User { id: Uuid, tags: Set, post_ids: List, } ``` -------------------------------- ### Defining Materialized View Model in Charybdis (Rust) Source: https://github.com/nodecosmos/charybdis/blob/main/charybdis-migrate/README.md This Rust snippet defines a materialized view model `UsersByUsername` using the `charybdis_view_model` macro. It specifies the base table (`users`), partition keys (`username`), and clustering keys (`id`), mapping fields to their respective Cassandra types. ```Rust 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, } ``` -------------------------------- ### Generated CQL Queries for Charybdis Collection Fields - Rust Source: https://github.com/nodecosmos/charybdis/blob/main/README.md This Rust `impl` block for the `User` struct demonstrates the static `&'static str` constants generated by Charybdis for `PUSH` and `PULL` operations on collection fields (`tags`, `post_ids`, `books_by_genre`). These constants represent the underlying CQL `UPDATE` statements used to add or remove elements from collections, expecting the collection value as the first bind parameter and primary key fields subsequently. ```Rust impl User { const PUSH_TAGS_QUERY: &'static str = "UPDATE users SET tags = tags + ? WHERE id = ?"; const PUSH_TAGS_IF_EXISTS_QUERY: &'static str = "UPDATE users SET tags = tags + ? WHERE id = ? IF EXISTS"; const PULL_TAGS_QUERY: &'static str = "UPDATE users SET tags = tags - ? WHERE id = ?"; const PULL_TAGS_IF_EXISTS_QUERY: &'static str = "UPDATE users SET tags = tags - ? WHERE id = ? IF EXISTS"; const PUSH_POST_IDS_QUERY: &'static str = "UPDATE users SET post_ids = post_ids + ? WHERE id = ?"; const PUSH_POST_IDS_IF_EXISTS_QUERY: &'static str = "UPDATE users SET post_ids = post_ids + ? WHERE id = ? IF EXISTS"; const PULL_POST_IDS_QUERY: &'static str = "UPDATE users SET post_ids = post_ids - ? WHERE id = ?"; const PULL_POST_IDS_IF_EXISTS_QUERY: &'static str = "UPDATE users SET post_ids = post_ids - ? WHERE id = ? IF EXISTS"; const PUSH_BOOKS_BY_GENRE_QUERY: &'static str = "UPDATE users SET books_by_genre = books_by_genre + ? WHERE id = ?"; const PUSH_BOOKS_BY_GENRE_IF_EXISTS_QUERY: &'static str = "UPDATE users SET books_by_genre = books_by_genre + ? WHERE id = ? IF EXISTS"; const PULL_BOOKS_BY_GENRE_QUERY: &'static str = "UPDATE users SET books_by_genre = books_by_genre - ? WHERE id = ?"; const PULL_BOOKS_BY_GENRE_IF_EXISTS_QUERY: &'static str = "UPDATE users SET books_by_genre = books_by_genre - ? WHERE id = ? IF EXISTS"; } ```