Skip to content

Easily Deserialize Postgres rows.

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

syntheticsh/serde_postgres

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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(())
}

About

Easily Deserialize Postgres rows.

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Rust 100.0%