Skip to content

Instantly share code, notes, and snippets.

@dcchut
Last active December 16, 2020 12:25
Show Gist options
  • Save dcchut/4e784869c034382d5ee7a1809a3d37ef to your computer and use it in GitHub Desktop.
Save dcchut/4e784869c034382d5ee7a1809a3d37ef to your computer and use it in GitHub Desktop.
Async version of serde_postgres
#![feature(async_await)]
/*
Cargo.toml dependencies:
serde = { version = "1.0", features = ["derive"] }
tokio = { git = "https://github.com/tokio-rs/tokio", default-features = false, features = ["io", "codec"] }
tokio-postgres = { git = "https://github.com/sfackler/rust-postgres", branch = "std-futures" }
futures-preview = { git = "https://github.com/rust-lang-nursery/futures-rs" , features = ["nightly", "async-await"] }
futures-util-preview = { version = "0.3.0-alpha.4", features = ["compat"] }
serde_tokio_postgres = { git = "https://github.com/dcchut/serde_postgres" }
*/
use futures_util::try_stream::TryStreamExt;
use futures_util::future::FutureExt;
use tokio_postgres::{NoTls, Error};
use serde_tokio_postgres::from_row;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
struct Person {
name : String,
data : Vec<u8>,
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let (mut client, connection) =
tokio_postgres::connect("host=localhost user=postgres password=password", NoTls).await?;
let connection = connection.map(|r| {
if let Err(e) = r {
eprintln!("connection error: {}", e);
}
});
tokio::spawn(connection);
let create_statement = client.prepare("CREATE TABLE IF NOT EXISTS person (\
id SERIAL,\
name VARCHAR NOT NULL,\
data BYTEA\
);").await?;
// Create our table
client.execute(&create_statement, &[]).await?;
let insert_statement = client.prepare("INSERT INTO person \
(name, data) VALUES ($1, $2)").await?;
// Insert our rows
client.execute(&insert_statement, &[&"Jane", &"My data".as_bytes()]).await?;
client.execute(&insert_statement, &[&"Alice", &"Alice's data".as_bytes()]).await?;
let query_statement = client.prepare("SELECT name, data FROM person").await?;
let rows = client.query(&query_statement, &[])
.map_ok(|r| from_row::<Person>(r).unwrap())
.try_collect::<Vec<_>>()
.await?;
dbg!(rows);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment