| 1 | use crate::column::ColumnIndex; |
| 2 | use crate::error::Error; |
| 3 | use crate::message::DataRow; |
| 4 | use crate::statement::PgStatementMetadata; |
| 5 | use crate::value::PgValueFormat; |
| 6 | use crate::{PgColumn, PgValueRef, Postgres}; |
| 7 | pub(crate) use sqlx_core::row::Row; |
| 8 | use sqlx_core::type_checking::TypeChecking; |
| 9 | use sqlx_core::value::ValueRef; |
| 10 | use std::fmt::Debug; |
| 11 | use std::sync::Arc; |
| 12 | |
| 13 | /// Implementation of [`Row`] for PostgreSQL. |
| 14 | pub struct PgRow { |
| 15 | pub(crate) data: DataRow, |
| 16 | pub(crate) format: PgValueFormat, |
| 17 | pub(crate) metadata: Arc<PgStatementMetadata>, |
| 18 | } |
| 19 | |
| 20 | impl Row for PgRow { |
| 21 | type Database = Postgres; |
| 22 | |
| 23 | fn columns(&self) -> &[PgColumn] { |
| 24 | &self.metadata.columns |
| 25 | } |
| 26 | |
| 27 | fn try_get_raw<I>(&self, index: I) -> Result<PgValueRef<'_>, Error> |
| 28 | where |
| 29 | I: ColumnIndex<Self>, |
| 30 | { |
| 31 | let index = index.index(self)?; |
| 32 | let column = &self.metadata.columns[index]; |
| 33 | let value = self.data.get(index); |
| 34 | |
| 35 | Ok(PgValueRef { |
| 36 | format: self.format, |
| 37 | row: Some(&self.data.storage), |
| 38 | type_info: column.type_info.clone(), |
| 39 | value, |
| 40 | }) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | impl ColumnIndex<PgRow> for &'_ str { |
| 45 | fn index(&self, row: &PgRow) -> Result<usize, Error> { |
| 46 | row.metadata |
| 47 | .column_names |
| 48 | .get(*self) |
| 49 | .ok_or_else(|| Error::ColumnNotFound((*self).into())) |
| 50 | .copied() |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | impl Debug for PgRow { |
| 55 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 56 | write!(f, "PgRow ")?; |
| 57 | |
| 58 | let mut debug_map = f.debug_map(); |
| 59 | for (index, column) in self.columns().iter().enumerate() { |
| 60 | match self.try_get_raw(index) { |
| 61 | Ok(value) => { |
| 62 | debug_map.entry( |
| 63 | &column.name, |
| 64 | &Postgres::fmt_value_debug(&<PgValueRef as ValueRef>::to_owned(&value)), |
| 65 | ); |
| 66 | } |
| 67 | Err(error) => { |
| 68 | debug_map.entry(&column.name, &format!("decode error: {error:?}")); |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | debug_map.finish() |
| 74 | } |
| 75 | } |