1use crate::database::Database;
2use either::Either;
3use std::convert::identity;
4
5#[derive(Debug)]
12#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
13#[cfg_attr(
14 feature = "offline",
15 serde(bound(
16 serialize = "DB::TypeInfo: serde::Serialize, DB::Column: serde::Serialize",
17 deserialize = "DB::TypeInfo: serde::de::DeserializeOwned, DB::Column: serde::de::DeserializeOwned",
18 ))
19)]
20#[doc(hidden)]
21pub struct Describe<DB: Database> {
22 pub columns: Vec<DB::Column>,
23 pub parameters: Option<Either<Vec<DB::TypeInfo>, usize>>,
24 pub nullable: Vec<Option<bool>>,
25}
26
27impl<DB: Database> Describe<DB> {
28 pub fn columns(&self) -> &[DB::Column] {
30 &self.columns
31 }
32
33 pub fn column(&self, index: usize) -> &DB::Column {
37 &self.columns[index]
38 }
39
40 pub fn parameters(&self) -> Option<Either<&[DB::TypeInfo], usize>> {
46 self.parameters.as_ref().map(|p| match p {
47 Either::Left(params) => Either::Left(&**params),
48 Either::Right(count) => Either::Right(*count),
49 })
50 }
51
52 pub fn nullable(&self, column: usize) -> Option<bool> {
54 self.nullable.get(column).copied().and_then(identity)
55 }
56}
57
58#[cfg(feature = "any")]
59impl<DB: Database> Describe<DB> {
60 #[doc(hidden)]
61 pub fn try_into_any(self) -> crate::Result<Describe<crate::any::Any>>
62 where
63 crate::any::AnyColumn: for<'a> TryFrom<&'a DB::Column, Error = crate::Error>,
64 crate::any::AnyTypeInfo: for<'a> TryFrom<&'a DB::TypeInfo, Error = crate::Error>,
65 {
66 use crate::any::AnyTypeInfo;
67
68 let columns = self
69 .columns
70 .iter()
71 .map(crate::any::AnyColumn::try_from)
72 .collect::<Result<Vec<_>, _>>()?;
73
74 let parameters = match self.parameters {
75 Some(Either::Left(parameters)) => Some(Either::Left(
76 parameters
77 .iter()
78 .enumerate()
79 .map(|(i, type_info)| {
80 AnyTypeInfo::try_from(type_info).map_err(|_| {
81 crate::Error::AnyDriverError(
82 format!(
83 "Any driver does not support type {type_info} of parameter {i}"
84 )
85 .into(),
86 )
87 })
88 })
89 .collect::<Result<Vec<_>, _>>()?,
90 )),
91 Some(Either::Right(count)) => Some(Either::Right(count)),
92 None => None,
93 };
94
95 Ok(Describe {
96 columns,
97 parameters,
98 nullable: self.nullable,
99 })
100 }
101}