Connessione a Cassandra in Rust

Mattepuffo's logo
Connessione a Cassandra in Rust

Connessione a Cassandra in Rust

In questo articolo vediamo come connetterci ad un db Cassandra in Rust.

Abbiamo due tabelle identiche:

  • in una salviamo tutti gli utenti (utenti_tutti)
  • nell'altra solo i maggiorenni (utenti_maggiorenni)

La strutture di entrambe le tabelle è questa:

  • id            uuid primary key
  • email         text
  • eta           int
  • nome_completo text

Queste sono le dipendenze che ci servono:

[dependencies]
scylla = "0.12.0"
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }

Qui sotto un pò di codice; ho messo tutto insieme per semplcitià:

use scylla::statement::prepared_statement::PreparedStatement;
use scylla::{Session, SessionBuilder};
use std::error::Error;
use uuid::Uuid;

struct Utente {
    id: Uuid,
    email: String,
    eta: i32,
    nome_completo: String,
}

impl Utente {
    fn new(email: &str, eta: i32, nome_completo: &str) -> Self {
        Self {
            id: Uuid::new_v4(),
            email: email.to_string(),
            eta,
            nome_completo: nome_completo.to_string(),
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let uri = "172.17.0.5:9042";
    let session: Session = SessionBuilder::new().known_node(uri).build().await?;

    println!("Connesso a Cassandra!");

    session.query("USE test_keyspace", ()).await?;

    let insert_tutti_stmt: PreparedStatement = session
        .prepare("INSERT INTO utenti_tutti (id, email, eta, nome_completo) VALUES (?, ?, ?, ?)")
        .await?;

    let insert_maggiorenni_stmt: PreparedStatement = session
        .prepare(
            "INSERT INTO utenti_maggiorenni (id, email, eta, nome_completo) VALUES (?, ?, ?, ?)",
        )
        .await?;

    let utenti = vec![
        Utente::new("mario.rossi@email.com", 25, "Mario Rossi"),
        Utente::new("giulia.verdi@email.com", 30, "Giulia Verdi"),
        Utente::new("luca.bianchi@email.com", 16, "Luca Bianchi"),
    ];

    println!("=== INSERIMENTO UTENTI ===");

    for utente in &utenti {
        let params = (
            &utente.id,
            &utente.email,
            &utente.eta,
            &utente.nome_completo,
        );

        session.execute(&insert_tutti_stmt, params).await?;
        println!(
            "Inserito in utenti_tutti: {} (età {})",
            utente.nome_completo, utente.eta
        );

        if utente.eta >= 18 {
            session.execute(&insert_maggiorenni_stmt, params).await?;
            println!("Inserito in utenti_maggiorenni: {}", utente.nome_completo);
        } else {
            println!(
                "NON inserito in utenti_maggiorenni: {} (minorenne)",
                utente.nome_completo
            );
        }

        println!("---");
    }

    println!("=== QUERY TABELLA: utenti_tutti ===");
    query_and_print_results(
        &session,
        "SELECT id, nome_completo, email, eta FROM utenti_tutti",
    )
    .await?;

    println!("=== QUERY TABELLA: utenti_maggiorenni ===");
    query_and_print_results(
        &session,
        "SELECT id, nome_completo, email, eta FROM utenti_maggiorenni",
    )
    .await?;

    println!("Operazioni completate");

    Ok(())
}

async fn query_and_print_results(session: &Session, cql: &str) -> Result<(), Box<dyn Error>> {
    let result = session.query(cql, ()).await?;

    if let Some(rows) = result.rows {
        println!("Totale righe trovate: {}", rows.len());
        for row in rows {
            let (id, nome, email, eta): (Uuid, String, String, i32) = row.into_typed()?;
            println!(
                "ID: {}Nome: {}Email: {}Età: {}---",
                id, nome, email, eta
            );
        }
    }

    Ok(())
}

Enjoy!


Condividi

Commentami!