#mapper #postgresql #tokio

tokio-pg-mapper

Proc-macro library used to map a tokio-postgres row to a Rust type (struct)

9 releases

0.2.0 Jan 4, 2021
0.1.9 Dec 31, 2020
0.1.8 May 26, 2020
0.1.7 Mar 26, 2020
0.1.4 Jan 11, 2020

#1293 in Database interfaces

Download history 968/week @ 2024-07-20 1067/week @ 2024-07-27 659/week @ 2024-08-03 1107/week @ 2024-08-10 759/week @ 2024-08-17 853/week @ 2024-08-24 1032/week @ 2024-08-31 821/week @ 2024-09-07 899/week @ 2024-09-14 1021/week @ 2024-09-21 898/week @ 2024-09-28 662/week @ 2024-10-05 769/week @ 2024-10-12 660/week @ 2024-10-19 811/week @ 2024-10-26 916/week @ 2024-11-02

3,235 downloads per month
Used in 5 crates (4 directly)

ISC license

11KB
57 lines

tokio-pg-mapper

tokio_postgres-mapper is a proc-macro designed to make mapping from postgresql tables to structs simple.

Why?

It can be frustrating to write a lot of boilerplate and, ultimately, duplicated code for mapping from postgres Rows into structs.

For example, this might be what someone would normally write:

extern crate postgres;

use postgres::rows::Row;

pub struct User {
    pub id: i64,
    pub name: String,
    pub email: Option<String>,
}

impl From<Row> for User {
    fn from(row: Row) -> Self {
        Self {
            id: row.get("id"),
            name: row.get("name"),
            email: row.get("email"),
        }
    }
}

// code to execute a query here and get back a row
let user = User::from(row); // this can panic

This becomes worse when manually implementating using the non-panicking get_opt method variant.

Using this crate, the boilerplate is removed, and panicking and non-panicking implementations are derived:

extern crate tokio_pg_mapper_derive;
extern crate tokio_pg_mapper;

use tokio_pg_mapper::FromTokioPostgresRow;
use tokio_pg_mapper_derive::PostgresMapper;

#[derive(PostgresMapper)]
pub struct User {
    pub id: i64,
    pub name: String,
    pub email: Option<String>,
}

// Code to execute a query here and get back a row might now look like:
let stmt = "SELECT * FROM user WHERE username = $1 AND password = $2";

let result = client.query_one(stmt, &[&5, "asdf"]).await?;
let user = User::from_row(result).unwrap(); // or from_row_ref(&result)


The two crates

This repository contains two crates: postgres-mapper which contains an Error enum and traits for converting from a tokio-postgres Row without panicking, and postgres-mapper-derive which contains the proc-macro.

Installation

Install tokio-pg-mapper-derive and tokio-pg-mapper from crates.io

License

ISC.

Dependencies

~7–16MB
~219K SLoC