5 releases

0.2.0 Aug 8, 2020
0.1.3 Mar 18, 2019
0.1.2 Dec 3, 2018
0.1.1 Dec 3, 2018
0.1.0 Nov 21, 2018

#1308 in Parser implementations

Download history 281/week @ 2023-11-20 451/week @ 2023-11-27 411/week @ 2023-12-04 473/week @ 2023-12-11 331/week @ 2023-12-18 30/week @ 2023-12-25 238/week @ 2024-01-01 527/week @ 2024-01-08 475/week @ 2024-01-15 593/week @ 2024-01-22 606/week @ 2024-01-29 520/week @ 2024-02-05 452/week @ 2024-02-12 535/week @ 2024-02-19 490/week @ 2024-02-26 421/week @ 2024-03-04

1,931 downloads per month

MIT/Apache

25KB
502 lines

Serde Postgres

Build status Crate Lines Of Code Documentation

Easily deserialize rows from tokio-postgres or postgres into arbitrary structs. (Only deserialization is supported).

Examples

tokio-postgres (asynchronous)

use std::error::Error;
use serde::Deserialize;
use tokio_postgres::{connect, NoTls};

#[derive(Clone, Debug, Deserialize)]
struct Person {
    name: String,
    age: i32,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let (client, connection) = connect("postgres://postgres@localhost:5432", NoTls).await?;
    tokio::spawn(connection);

    client.execute("CREATE TABLE IF NOT EXISTS Person (
        name VARCHAR NOT NULL,
        age INT NOT NULL
    )", &[]).await?;

    client.execute("INSERT INTO Person (name, age) VALUES ($1, $2)",
                       &[&"Jane", &23i32]).await?;

    client.execute("INSERT INTO Person (name, age) VALUES ($1, $2)",
                       &[&"Alice", &32i32]).await?;

    let rows = client.query("SELECT name, age FROM Person", &[]).await?;

    let people: Vec<Person> = serde_postgres::from_rows(&rows)?;

    for person in people {
        println!("{:?}", person);
    }

    Ok(())
}

postgres (synchronous)

use postgres::{Client, NoTls};
use serde::Deserialize;
use std::error::Error;

#[derive(Clone, Debug, Deserialize)]
struct Person {
    name: String,
    age: i32,
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut client = Client::connect("postgres://postgres@localhost:5432", NoTls)?;

    client.execute("CREATE TABLE IF NOT EXISTS Person (
        name VARCHAR NOT NULL,
        age INT NOT NULL
    )", &[])?;

    client.execute("INSERT INTO Person (name, age) VALUES ($1, $2)",
                   &[&"Jane", &23i32])?;
    
    client.execute("INSERT INTO Person (name, age) VALUES ($1, $2)",
                   &[&"Alice", &32i32])?;

    let rows = client.query("SELECT name, age FROM Person", &[])?;

    let people: Vec<Person> = serde_postgres::from_rows(&rows)?;

    for person in people {
        println!("{:?}", person);
    }

    Ok(())
}

Dependencies

~11MB
~277K SLoC