#postgres #postgresql #from-row #mapper #postgres-tokio


Derivable trait that allows converting a postgres row to a struct

7 releases (4 breaking)

0.5.2 May 26, 2023
0.5.1 Jan 19, 2023
0.4.0 Jan 10, 2023
0.3.0 Jan 10, 2023
0.1.0 Oct 25, 2022

#390 in Database interfaces

Download history 80/week @ 2023-08-14 127/week @ 2023-08-21 38/week @ 2023-08-28 41/week @ 2023-09-04 47/week @ 2023-09-11 91/week @ 2023-09-18 83/week @ 2023-09-25 51/week @ 2023-10-02 59/week @ 2023-10-09 105/week @ 2023-10-16 75/week @ 2023-10-23 146/week @ 2023-10-30 112/week @ 2023-11-06 200/week @ 2023-11-13 150/week @ 2023-11-20 75/week @ 2023-11-27

595 downloads per month

Custom license



Derive FromRow to generate a mapping between a struct and postgres rows.

This crate is compatible with both postgres and tokio-postgres.

postgres_from_row = "0.5.2"


use postgres_from_row::FromRow;

struct Todo {
    todo_id: i32,
    text: String
    author_id: i32,

let row = client.query_one("SELECT todo_id, text, author_id FROM todos", &[]).unwrap();

// Pass a row with the correct columns.
let todo = Todo::from_row(&row);

let row = client.query_one("SELECT foo FROM bar", &[]).unwrap();

// Use `try_from_row` if the operation could fail.
let todo = Todo::try_from_row(&row);

Each field need's to implement postgres::types::FromSql, as this will be used to convert a single column to the specified type. If you want to override this behavior and delegate it to a nested structure that also implements FromRow, use #[from_row(flatten)]:

use postgres_from_row::FromRow;

struct Todo {
    todo_id: i32,
    text: String,
    author: User

struct User {
    user_id: i32,
    username: String

let row = client.query_one("SELECT todo_id, text, user_id, username FROM todos t, users u WHERE t.author_id = u.user_id", &[]).unwrap();
let todo = Todo::from_row(&row);

If a the struct contains a field with a name that differs from the name of the sql column, you can use the #[from_row(rename = "..")] attribute.

When a field in your struct has a type T that doesn't implement FromSql or FromRow but it does impement T: From<C> or T: TryFrom<c>, and C does implment FromSql or FromRow you can use #[from_row(from = "C")] or #[from_row(try_from = "C")]. This will use type C to extract it from the row and then finally converts it into T.

struct Todo {
    // If the postgres column is named `todo_id`.
    #[from_row(rename = "todo_id")]
    id: i32,
    // If the postgres column is `VARCHAR`, it will be decoded to `String`,
    // using `FromSql` and then converted to `Vec<u8>` using `std::convert::From`.
    #[from_row(from = "String")]
    todo: Vec<u8>


~319K SLoC