#postgresql #mapper #tokio

macro tokio-pg-mapper-derive

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

4 releases

0.2.0 Jan 4, 2021
0.1.6 Dec 30, 2020
0.1.5 Mar 2, 2020
0.1.4 Jan 11, 2020
0.1.0 Jan 10, 2020

#57 in #mapper

Download history 1319/week @ 2025-10-15 930/week @ 2025-10-22 847/week @ 2025-10-29 900/week @ 2025-11-05 803/week @ 2025-11-12 955/week @ 2025-11-19 1063/week @ 2025-11-26 878/week @ 2025-12-03 948/week @ 2025-12-10 832/week @ 2025-12-17 903/week @ 2025-12-24 973/week @ 2025-12-31 685/week @ 2026-01-07 884/week @ 2026-01-14 822/week @ 2026-01-21 860/week @ 2026-01-28

3,403 downloads per month
Used in 7 crates (6 directly)

ISC license

8KB
159 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–19MB
~222K SLoC