Skip to main content

Rust

Relyt supports the PostgreSQL connection protocol, which means any tools or software that can connect to PostgreSQL can also be used for Relyt connections.

This guide will walk you through the process of connecting to Relyt using Rust.

info

The OS used in the following example is MacOS. If you use other types of OS, change the code accordingly.

1. Prepare the environment

  1. Install Rust and Cargo in your environment.

    tip

    Skip this step if your environment is ready.

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  2. Restart your command line tool and check the Rust and Cargo versions:

    rustc --version
    cargo --version

2. Create a Rust program

  1. Create a Rust project:

    cargo new relyt_demo
  2. Go to the Rust project directory and add tokio and postgres dependencies to the Cargo.toml file:

    cd relyt_demo
    vim Cargo.toml
    [dependencies]
    tokio = { version = "1", features = ["full"] }
    tokio-postgres = "0.7"
  3. Enter the src directory, and replace the content in the main.rs file with the following code:

    use tokio_postgres::{NoTls, Error};

    #[tokio::main]
    async fn main() -> Result<(), Error> {
    let (client, connection) =
    tokio_postgres::connect("host=<endpoint_domain> port=<endpoint_port> dbname=<database> user=<dw_user> password=<dw_user_password>", NoTls).await?;

    tokio::spawn(async move {
    if let Err(e) = connection.await {
    eprintln!("connection error: {}", e);
    }
    });

    client.batch_execute("
    DROP TABLE IF EXISTS items;
    CREATE TABLE IF NOT EXISTS items (id INTEGER, name VARCHAR);
    INSERT INTO items (id, name) VALUES (1, 'item1'), (2, 'item2');
    ").await?;

    let rows = client.query("SELECT * FROM items", &[]).await?;

    for row in &rows {
    let id: i32 = row.get(0);
    let name: &str = row.get(1);
    println!("id: {}, name: {}", id, name);
    }

    Ok(())
    }

    The following table describes the related parameters. Specify them based on your actual conditions.

    ParameterDescription
    hostThe public endpoint for connecting to the Relyt DW service unit.
    portThe port for connecting to the Relyt DW service unit. The default port is 5432.
    dbnameThe name of the Relyt database to connect.
    userThe name of the DW user that connects to the Relyt DW service unit.
    passwordThe password of the DW user.

    The SQL commands provided in the example perform the following operations in sequence:

    • Drop a table named items if it exists

    • Create a table named items

    • Insert data to table items

    • Query data from items

    They are for reference only. You can replace them with any SQL commands you want to run.

3. Run the program

Open the directory that stores the Cargo.toml file. Then, run the following commands to build and run the program:

cargo build
cargo run