I have a PostgreSQL database with one simple table:
CREATE DATABASE test_database;
\c test_database;
CREATE TABLE users ( id int primary key NOT NULL, name varchar(40) NOT NULL );
INSERT INTO users (id,name) VALUES (1, 'user_one');
INSERT INTO users (id,name) VALUES (2, 'user_two');
Now I want to write a rust program that retrieves users with SELECT id, name FROM users
and returns them.
For this I picked tokio_postgres
, as it is asynchronous and it seems to have support with Tokio async runtime.
This is my program:
mod domain;
mod types;
use tokio_postgres::NoTls;
use types::AsyncResult;
// Using Tokio runtime for async behaviour: https://crates.io/crates/tokio
#[tokio::main]
async fn main() -> AsyncResult<()> {
// Get DB client and connection
let (client, connection) = tokio_postgres::connect(
"postgres://test_user:secret_password@localhost/test_database",
NoTls,
)
.await?;
// Spawn connection
tokio::spawn(async move {
if let Err(error) = connection.await {
eprintln!("Connection error: {}", error);
}
});
// Do the query
let users = client.query("SELECT id, name FROM users", &[]).await?;
println!("{:#?}", users);
Ok(())
}
From this I expect to get something similar to:
[
{
"id": 1,
"name": "user_1"
},
{
"id": 2,
"name": "user_2"
}
]
But instead I receive the table structure:
[
Row {
columns: [
Column {
name: "id",
type: Int4,
},
Column {
name: "name",
type: Varchar,
},
],
},
Row {
columns: [
Column {
name: "id",
type: Int4,
},
Column {
name: "name",
type: Varchar,
},
],
},
]
I tried everything, but I cant't see what I'm doing wrong.