Skip to main content

cufflink_pgcodec/
render.rs

1//! A statement's rows as a guest receives them.
2
3use crate::row_json::{column_to_json, column_to_json_v2};
4use cufflink_types::db::{Column, DbError, DbResponse, RowMap};
5use serde_json::Value;
6use tokio_postgres::Row;
7
8/// The rows of a legacy query: an object per row, each column under its
9/// name in the legacy encoding.
10pub fn legacy_rows(rows: &[Row]) -> Vec<Value> {
11    rows.iter()
12        .map(|row| {
13            Value::Object(
14                row.columns()
15                    .iter()
16                    .enumerate()
17                    .map(|(i, column)| {
18                        (
19                            column.name().to_string(),
20                            column_to_json(row, i, column.type_()),
21                        )
22                    })
23                    .collect(),
24            )
25        })
26        .collect()
27}
28
29/// The rows of a `db_call` query with the columns its statement reports;
30/// a value the exact encoding cannot carry is the error.
31pub fn rows_v2(columns: &[tokio_postgres::Column], rows: &[Row]) -> Result<DbResponse, DbError> {
32    let rows = rows
33        .iter()
34        .map(|row| {
35            columns
36                .iter()
37                .enumerate()
38                .map(|(i, column)| {
39                    column_to_json_v2(row, i, column.type_())
40                        .map(|value| (column.name().to_string(), value))
41                })
42                .collect::<Result<RowMap, DbError>>()
43        })
44        .collect::<Result<Vec<_>, _>>()?;
45    Ok(DbResponse::Rows {
46        rows,
47        columns: columns
48            .iter()
49            .map(|column| Column {
50                name: column.name().to_string(),
51                type_name: column.type_().name().to_string(),
52            })
53            .collect(),
54    })
55}