Skip to content

Commit

Permalink
book: improve documentation about UDT values
Browse files Browse the repository at this point in the history
This change aims to improve the documentation
about handling user defined types in the Rust driver.

Changes:
* Mention that fields in UDT and Rust struct must be in the same order
* Add a link to official Scylla docs about UDTs
* Improve grammar, make it clearer

Signed-off-by: Jan Ciolek <[email protected]>
  • Loading branch information
cvybhu committed Aug 18, 2023
1 parent 5aeb080 commit a097b93
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions docs/source/data-types/udt.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
# User defined types
Scylla allows users to define their own data types with named fields.\
The driver supports this by allowing to create a custom struct with derived functionality.
Scylla allows users to define their own data types with named fields (See [the official documentation](https://opensource.docs.scylladb.com/stable/cql/types.html#user-defined-types))\
To use user defined types in the driver, you can create a corresponding struct in Rust, and use it to read and write UDT values.


For example let's say `my_type` was created using this query:
```sql
CREATE TYPE ks.my_type (int_val int, text_val text)
```

To use this type in the driver create a matching struct and derive `IntoUserType` and `FromUserType`:
To use this type in the driver, create a matching struct and derive `IntoUserType` and `FromUserType`:

```rust
# extern crate scylla;
# async fn check_only_compiles() {
use scylla::macros::{FromUserType, IntoUserType};

// Define a custom struct that matches the User Defined Type created earlier.
// Fields must be in the same order as they are in the database.
// Wrapping a field in Option will gracefully handle null field values.
#[derive(Debug, IntoUserType, FromUserType)]
struct MyType {
int_val: i32,
text_val: Option<String>,
}
# }
```

> ***Important***\
> Fields in the Rust struct must be defined in the same order as they are in the database.
> When sending and receiving values, the driver will (de)serialize fields one after another, without looking at field names.
Now it can be sent and received just like any other CQL value:
```rust
# extern crate scylla;
# use scylla::Session;
Expand All @@ -17,16 +40,12 @@ use scylla::IntoTypedRows;
use scylla::macros::{FromUserType, IntoUserType};
use scylla::cql_to_rust::FromCqlVal;

// Define custom struct that matches User Defined Type created earlier
// wrapping field in Option will gracefully handle null field values
#[derive(Debug, IntoUserType, FromUserType)]
struct MyType {
int_val: i32,
text_val: Option<String>,
}

// Now it can be sent and received like any other value

// Insert my_type into the table
let to_insert = MyType {
int_val: 17,
Expand Down

0 comments on commit a097b93

Please sign in to comment.