use scylla::{Session, SessionBuilder, SerializeValue, DeserializeValue};
use std::error::Error;
#[derive(Debug, SerializeValue, DeserializeValue)]
struct Address {
street: String,
city: String,
zip_code: Option<String>,
country: String,
}
#[derive(Debug, SerializeValue, DeserializeValue)]
struct User {
name: String,
email: String,
address: Address,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.build()
.await?;
// Create keyspace and type
session.query_unpaged(
"CREATE KEYSPACE IF NOT EXISTS my_keyspace WITH REPLICATION = {
'class': 'SimpleStrategy',
'replication_factor': 1
}",
&[],
).await?;
session.query_unpaged("USE my_keyspace", &[]).await?;
session.query_unpaged(
"CREATE TYPE IF NOT EXISTS address (
street text,
city text,
zip_code text,
country text
)",
&[],
).await?;
session.query_unpaged(
"CREATE TABLE IF NOT EXISTS users (
id int PRIMARY KEY,
name text,
email text,
address address
)",
&[],
).await?;
// Insert a user
let user = User {
name: "Alice".to_string(),
email: "[email protected]".to_string(),
address: Address {
street: "123 Main St".to_string(),
city: "Springfield".to_string(),
zip_code: Some("12345".to_string()),
country: "USA".to_string(),
},
};
session.query_unpaged(
"INSERT INTO users (id, name, email, address) VALUES (?, ?, ?, ?)",
(1, &user.name, &user.email, &user.address),
).await?;
// Read back
let result = session
.query_unpaged("SELECT name, email, address FROM users WHERE id = 1", &[])
.await?;
if let Some(row) = result.rows()?.first() {
println!("User: {:?}", row);
}
Ok(())
}