1use crate::util::extract_value;
2use postgres_types::{FromSql, Type};
3use std::{
4 borrow::Cow,
5 cmp::min,
6 error::Error,
7 fmt::{self, Debug, Formatter},
8 future::Future,
9 mem,
10 pin::Pin,
11 task::{Context, Poll},
12};
13use tank_core::{Error as TankError, Result, Row, RowLabels, Value, stream::Stream};
14
15struct RawCell<'a>(Option<&'a [u8]>);
16
17impl<'a> FromSql<'a> for RawCell<'a> {
18 #[inline(always)]
19 fn from_sql(
20 _t: &Type,
21 raw: &'a [u8],
22 ) -> std::result::Result<Self, Box<dyn Error + Sync + Send>> {
23 Ok(Self(Some(raw)))
24 }
25
26 #[inline(always)]
27 fn from_sql_null(_t: &Type) -> std::result::Result<Self, Box<dyn Error + Sync + Send>> {
28 Ok(Self(None))
29 }
30
31 #[inline(always)]
32 fn from_sql_nullable(
33 _t: &Type,
34 raw: Option<&'a [u8]>,
35 ) -> std::result::Result<Self, Box<dyn Error + Sync + Send>> {
36 Ok(Self(raw))
37 }
38
39 #[inline(always)]
40 fn accepts(_t: &Type) -> bool {
41 true
42 }
43}
44
45pub struct PostgresRow<'a> {
47 pub(crate) row: tokio_postgres::Row,
48 pub(crate) labels: &'a RowLabels,
49}
50
51impl Debug for PostgresRow<'_> {
52 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
53 f.debug_struct("PostgresRow")
54 .field("labels", &self.labels)
55 .field("len", &self.len())
56 .finish()
57 }
58}
59
60impl PostgresRow<'_> {
61 #[cold]
62 #[inline(never)]
63 fn decode_fallback<'a>(ty: &Type, raw: &'a [u8]) -> Option<Value<'a>> {
64 extract_value(ty, Some(raw)).ok()
65 }
66}
67
68impl Row for PostgresRow<'_> {
69 #[inline(always)]
70 fn labels(&self) -> &[String] {
71 self.labels
72 }
73
74 #[inline(always)]
75 fn len(&self) -> usize {
76 min(self.labels.len(), self.row.len())
77 }
78
79 #[inline(always)]
80 fn value(&self, index: usize) -> Option<Cow<'_, Value<'_>>> {
81 if index >= self.len() {
82 return None;
83 }
84 let raw = match self.row.try_get::<usize, RawCell<'_>>(index) {
85 Ok(RawCell(Some(raw))) => raw,
86 Ok(RawCell(None)) => return Some(Cow::Owned(Value::Null)),
87 Err(e) => {
88 mem::forget(e);
89 return None;
90 }
91 };
92 match *self.row.columns()[index].type_() {
95 Type::BOOL => match *raw {
96 [b] => Some(Cow::Owned(Value::Boolean(Some(b != 0)))),
97 _ => Some(Cow::Owned(Value::Null)),
98 },
99 Type::INT4 => match raw.try_into() {
100 Ok(b) => Some(Cow::Owned(Value::Int32(Some(i32::from_be_bytes(b))))),
101 Err(_) => Some(Cow::Owned(Value::Null)),
102 },
103 Type::VARCHAR | Type::TEXT => match std::str::from_utf8(raw) {
104 Ok(text) => Some(Cow::Owned(Value::Varchar(Some(Cow::Borrowed(text))))),
105 Err(_) => Some(Cow::Owned(Value::Null)),
106 },
107 ref ty => match Self::decode_fallback(ty, raw) {
108 Some(v) => Some(Cow::Owned(v)),
109 None => Some(Cow::Owned(Value::Null)),
110 },
111 }
112 }
113}
114
115pub struct PostgresRows<'s> {
117 first: Option<tokio_postgres::Row>,
118 stream: tokio_postgres::RowStream,
119 labels: &'s RowLabels,
120 done: bool,
124}
125
126impl<'s> PostgresRows<'s> {
127 #[inline(always)]
128 pub(crate) const fn new(
129 first: Option<tokio_postgres::Row>,
130 stream: tokio_postgres::RowStream,
131 labels: &'s RowLabels,
132 ) -> Self {
133 Self {
134 first,
135 stream,
136 labels,
137 done: false,
138 }
139 }
140
141 #[inline(always)]
142 pub(crate) const fn new_drained(
143 stream: tokio_postgres::RowStream,
144 labels: &'s RowLabels,
145 ) -> Self {
146 Self {
147 first: None,
148 stream,
149 labels,
150 done: true,
151 }
152 }
153
154 #[cold]
155 #[inline(never)]
156 fn row_error(e: tokio_postgres::Error) -> TankError {
157 let error = TankError::new(e);
158 log::error!("{error:#}");
159 error
160 }
161
162 #[inline(always)]
163 fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<PostgresRow<'s>>>> {
164 if self.done {
165 return Poll::Ready(None);
166 }
167 if let Some(row) = self.first.take() {
168 return Poll::Ready(Some(Ok(PostgresRow {
169 row,
170 labels: self.labels,
171 })));
172 }
173 match unsafe { Pin::new_unchecked(&mut self.stream) }.poll_next(cx) {
174 Poll::Ready(Some(Ok(row))) => Poll::Ready(Some(Ok(PostgresRow {
175 row,
176 labels: self.labels,
177 }))),
178 Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(Self::row_error(e)))),
179 Poll::Ready(None) => Poll::Ready(None),
180 Poll::Pending => Poll::Pending,
181 }
182 }
183}
184
185pub(crate) struct PostgresStream<'s, F> {
187 fut: Option<F>,
188 rows: Option<PostgresRows<'s>>,
189}
190
191impl<'s, F> PostgresStream<'s, F> {
192 #[inline(always)]
193 pub(crate) const fn new(fut: F) -> Self {
194 Self {
195 fut: Some(fut),
196 rows: None,
197 }
198 }
199
200 #[cold]
201 #[inline(never)]
202 fn poll_init(&mut self, cx: &mut Context<'_>) -> Poll<Result<()>>
203 where
204 F: Future<Output = Result<PostgresRows<'s>>>,
205 {
206 let Some(fut) = self.fut.as_mut() else {
207 return Poll::Ready(Ok(()));
208 };
209 let Poll::Ready(res) = unsafe { Pin::new_unchecked(fut) }.poll(cx) else {
210 return Poll::Pending;
211 };
212 self.fut = None;
213 self.rows = Some(res?);
214 Poll::Ready(Ok(()))
215 }
216}
217
218impl<'s, F> Stream for PostgresStream<'s, F>
219where
220 F: Future<Output = Result<PostgresRows<'s>>>,
221{
222 type Item = Result<PostgresRow<'s>>;
223
224 #[inline(always)]
225 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
226 let this = unsafe { self.get_unchecked_mut() };
227 if this.rows.is_none() {
228 match this.poll_init(cx) {
229 Poll::Ready(Ok(())) => {}
230 Poll::Ready(Err(e)) => return Poll::Ready(Some(Err(e))),
231 Poll::Pending => return Poll::Pending,
232 }
233 }
234 unsafe { this.rows.as_mut().unwrap_unchecked() }.poll_next(cx)
235 }
236}