Crate pgde

Source
Expand description

A simple library for consuming tokio_postgres::row::Row data into structs that derive the RowConsumer trait.

This crate provides a variety of derivable implementations that can be used to consume PostgreSQL data depending on preference.

  • from_row
  • from_rows
  • consume
  • consume_json if feature consume_json is enabled

The latter implementations are built from from_row.

§Features

A variety of features provide support for additional implementation and types.

FeatureDescriptionExtra dependenciesDefault
bitImplements crate on bit_vec::BitVecbit-vecNo
chronoImplements crate on types supplied by chronochronoNo
consume_jsonImplements consume_json on classes that derive the RowConsumer traitserde, serde_jsonNo
geoImplements crate on geo_types::Point<f64>, geo_types::Rect<f64>, and geo_types::LineString<f64>geo-typesNo
macImplements crate on eui48::MacAddresseui48No
jsonImplements crate on serde_json::Valueserde_jsonNo
timeImplements crate on types supplied by timetimeNo
uuidImplements crate on uuid::UuiduuidNo

§Examples

You may use consume to consume PostgreSQL row data into a struct like so.

use pgde::ConsumeError;
use pgde::RowConsumer;
use pgde_derive::RowConsumer;
use tokio_postgres::{NoTls, Row};

#[derive(RowConsumer)]
struct Foo {
    Id: i32,
    Data: String,
}

match tokio_postgres::connect("host=localhost user=postgres password=password dbname=postgres", NoTls).await {
    Ok(v) => {
        let client = v.0;
        let conn = v.1;

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

        let query = "select * from public.\"Foo\";";

        match Foo::consume(&client, query, &[]).await {
            Ok(v) => { // v is of type Vec<Foo>
                match v.first() {
                    Some(v) => println!("Id {} has Data {}", v.Id, v.Data),
                    None => eprintln!("No data in table"),
                }
            },
            Err(v) => match v {
                ConsumeError::ConversionError => eprintln!("Could not convert data"),
                ConsumeError::DatabaseConnectionError => eprintln!("Database errored on processing the query"),
            },
        };
    },
    Err(_) => eprintln!("Could not connect to database"),
};

Types of Vec<T> and Option<T>, where T implements FromSql, are also supported on structs, or as standalone consuming types, that derive RowConsumer. When querying nullable fields, it is best to wrap field types in an Option<>. See the RowConsumer trait for use examples of from_row and from_rows.

This crate also provides implementations on a variety of data types, some provided by enabling features.

TypeFeature
booldefault
i8default
i16default
i32default
u32default
i64default
f32default
f64default
Vec<u8>default
Stringdefault
SystemTimedefault
IpAddrdefault
bit_vec::BitVecbit
chrono::NaiveDateTimechrono
chrono::DateTime<Utc>chrono
chrono::DateTime<Local>chrono
chrono::DateTime<FixedOffset>chrono
chrono::NaiveDatechrono
chrono::NaiveTimechrono
geo_types::Point<f64>geo
geo_types::Rect<f64>geo
geo_types::LineString<f64>geo
eui48::MacAddressmac
serde_json::Valuejson
time::PrimitiveDateTimetime
time::OffsetDateTimetime
time::Datetime
time::Timetime
uuid::Uuiduuid

§Testing

Testing requires access to a PostgreSQL database with no tables. Setting the following environment variables will allow you to test.

Environment VariableDescription
PGDE_DB_HOSTThe host that the database can be accessed at.
POSTGRES_USERThe user credential to provide.
POSTGRES_PASSWORDThe password to provide.
POSTGRES_DBThe name of the database to use for testing.

Macros§

pg_type_expr_implementation
A macro for implementing from_row on primitive types or types outside of this crate that implement FromSql. Used internally to implement from_row on SystemTime and IpAddr.
pg_type_implementation
A macro for implementing from_row on primitive types or types outside of this crate that implement FromSql. Used internally to implement from_row on bool, i32, String, etc.

Enums§

ConsumeError
Errors that may occur during row consumption.

Traits§

RowConsumer
The derivable trait for implementing PostgreSQL row consumption.