| 1 | use crate::{ |
| 2 | Either, PgColumn, PgConnectOptions, PgConnection, PgQueryResult, PgRow, PgTransactionManager, |
| 3 | PgTypeInfo, Postgres, |
| 4 | }; |
| 5 | use futures_core::future::BoxFuture; |
| 6 | use futures_core::stream::BoxStream; |
| 7 | use futures_util::{stream, StreamExt, TryFutureExt, TryStreamExt}; |
| 8 | use std::future; |
| 9 | |
| 10 | use sqlx_core::any::{ |
| 11 | Any, AnyArguments, AnyColumn, AnyConnectOptions, AnyConnectionBackend, AnyQueryResult, AnyRow, |
| 12 | AnyStatement, AnyTypeInfo, AnyTypeInfoKind, |
| 13 | }; |
| 14 | |
| 15 | use crate::type_info::PgType; |
| 16 | use sqlx_core::connection::Connection; |
| 17 | use sqlx_core::database::Database; |
| 18 | use sqlx_core::describe::Describe; |
| 19 | use sqlx_core::executor::Executor; |
| 20 | use sqlx_core::ext::ustr::UStr; |
| 21 | use sqlx_core::transaction::TransactionManager; |
| 22 | |
| 23 | sqlx_core::declare_driver_with_optional_migrate!(DRIVER = Postgres); |
| 24 | |
| 25 | impl AnyConnectionBackend for PgConnection { |
| 26 | fn name(&self) -> &str { |
| 27 | <Postgres as Database>::NAME |
| 28 | } |
| 29 | |
| 30 | fn close(self: Box<Self>) -> BoxFuture<'static, sqlx_core::Result<()>> { |
| 31 | Connection::close(*self) |
| 32 | } |
| 33 | |
| 34 | fn close_hard(self: Box<Self>) -> BoxFuture<'static, sqlx_core::Result<()>> { |
| 35 | Connection::close_hard(*self) |
| 36 | } |
| 37 | |
| 38 | fn ping(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { |
| 39 | Connection::ping(self) |
| 40 | } |
| 41 | |
| 42 | fn begin(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { |
| 43 | PgTransactionManager::begin(self) |
| 44 | } |
| 45 | |
| 46 | fn commit(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { |
| 47 | PgTransactionManager::commit(self) |
| 48 | } |
| 49 | |
| 50 | fn rollback(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { |
| 51 | PgTransactionManager::rollback(self) |
| 52 | } |
| 53 | |
| 54 | fn start_rollback(&mut self) { |
| 55 | PgTransactionManager::start_rollback(self) |
| 56 | } |
| 57 | |
| 58 | fn shrink_buffers(&mut self) { |
| 59 | Connection::shrink_buffers(self); |
| 60 | } |
| 61 | |
| 62 | fn flush(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> { |
| 63 | Connection::flush(self) |
| 64 | } |
| 65 | |
| 66 | fn should_flush(&self) -> bool { |
| 67 | Connection::should_flush(self) |
| 68 | } |
| 69 | |
| 70 | #[cfg(feature = "migrate")] |
| 71 | fn as_migrate( |
| 72 | &mut self, |
| 73 | ) -> sqlx_core::Result<&mut (dyn sqlx_core::migrate::Migrate + Send + 'static)> { |
| 74 | Ok(self) |
| 75 | } |
| 76 | |
| 77 | fn fetch_many<'q>( |
| 78 | &'q mut self, |
| 79 | query: &'q str, |
| 80 | persistent: bool, |
| 81 | arguments: Option<AnyArguments<'q>>, |
| 82 | ) -> BoxStream<'q, sqlx_core::Result<Either<AnyQueryResult, AnyRow>>> { |
| 83 | let persistent = persistent && arguments.is_some(); |
| 84 | let arguments = match arguments.as_ref().map(AnyArguments::convert_to).transpose() { |
| 85 | Ok(arguments) => arguments, |
| 86 | Err(error) => { |
| 87 | return stream::once(future::ready(Err(sqlx_core::Error::Encode(error)))).boxed() |
| 88 | } |
| 89 | }; |
| 90 | |
| 91 | Box::pin( |
| 92 | self.run(query, arguments, 0, persistent, None) |
| 93 | .try_flatten_stream() |
| 94 | .map( |
| 95 | move |res: sqlx_core::Result<Either<PgQueryResult, PgRow>>| match res? { |
| 96 | Either::Left(result) => Ok(Either::Left(map_result(result))), |
| 97 | Either::Right(row) => Ok(Either::Right(AnyRow::try_from(&row)?)), |
| 98 | }, |
| 99 | ), |
| 100 | ) |
| 101 | } |
| 102 | |
| 103 | fn fetch_optional<'q>( |
| 104 | &'q mut self, |
| 105 | query: &'q str, |
| 106 | persistent: bool, |
| 107 | arguments: Option<AnyArguments<'q>>, |
| 108 | ) -> BoxFuture<'q, sqlx_core::Result<Option<AnyRow>>> { |
| 109 | let persistent = persistent && arguments.is_some(); |
| 110 | let arguments = arguments |
| 111 | .as_ref() |
| 112 | .map(AnyArguments::convert_to) |
| 113 | .transpose() |
| 114 | .map_err(sqlx_core::Error::Encode); |
| 115 | |
| 116 | Box::pin(async move { |
| 117 | let arguments = arguments?; |
| 118 | let stream = self.run(query, arguments, 1, persistent, None).await?; |
| 119 | futures_util::pin_mut!(stream); |
| 120 | |
| 121 | if let Some(Either::Right(row)) = stream.try_next().await? { |
| 122 | return Ok(Some(AnyRow::try_from(&row)?)); |
| 123 | } |
| 124 | |
| 125 | Ok(None) |
| 126 | }) |
| 127 | } |
| 128 | |
| 129 | fn prepare_with<'c, 'q: 'c>( |
| 130 | &'c mut self, |
| 131 | sql: &'q str, |
| 132 | _parameters: &[AnyTypeInfo], |
| 133 | ) -> BoxFuture<'c, sqlx_core::Result<AnyStatement<'q>>> { |
| 134 | Box::pin(async move { |
| 135 | let statement = Executor::prepare_with(self, sql, &[]).await?; |
| 136 | AnyStatement::try_from_statement( |
| 137 | sql, |
| 138 | &statement, |
| 139 | statement.metadata.column_names.clone(), |
| 140 | ) |
| 141 | }) |
| 142 | } |
| 143 | |
| 144 | fn describe<'q>(&'q mut self, sql: &'q str) -> BoxFuture<'q, sqlx_core::Result<Describe<Any>>> { |
| 145 | Box::pin(async move { |
| 146 | let describe = Executor::describe(self, sql).await?; |
| 147 | |
| 148 | let columns = describe |
| 149 | .columns |
| 150 | .iter() |
| 151 | .map(AnyColumn::try_from) |
| 152 | .collect::<Result<Vec<_>, _>>()?; |
| 153 | |
| 154 | let parameters = match describe.parameters { |
| 155 | Some(Either::Left(parameters)) => Some(Either::Left( |
| 156 | parameters |
| 157 | .iter() |
| 158 | .enumerate() |
| 159 | .map(|(i, type_info)| { |
| 160 | AnyTypeInfo::try_from(type_info).map_err(|_| { |
| 161 | sqlx_core::Error::AnyDriverError( |
| 162 | format!( |
| 163 | "Any driver does not support type {type_info} of parameter {i}" |
| 164 | ) |
| 165 | .into(), |
| 166 | ) |
| 167 | }) |
| 168 | }) |
| 169 | .collect::<Result<Vec<_>, _>>()?, |
| 170 | )), |
| 171 | Some(Either::Right(count)) => Some(Either::Right(count)), |
| 172 | None => None, |
| 173 | }; |
| 174 | |
| 175 | Ok(Describe { |
| 176 | columns, |
| 177 | parameters, |
| 178 | nullable: describe.nullable, |
| 179 | }) |
| 180 | }) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | impl<'a> TryFrom<&'a PgTypeInfo> for AnyTypeInfo { |
| 185 | type Error = sqlx_core::Error; |
| 186 | |
| 187 | fn try_from(pg_type: &'a PgTypeInfo) -> Result<Self, Self::Error> { |
| 188 | Ok(AnyTypeInfo { |
| 189 | kind: match &pg_type.0 { |
| 190 | PgType::Bool => AnyTypeInfoKind::Bool, |
| 191 | PgType::Void => AnyTypeInfoKind::Null, |
| 192 | PgType::Int2 => AnyTypeInfoKind::SmallInt, |
| 193 | PgType::Int4 => AnyTypeInfoKind::Integer, |
| 194 | PgType::Int8 => AnyTypeInfoKind::BigInt, |
| 195 | PgType::Float4 => AnyTypeInfoKind::Real, |
| 196 | PgType::Float8 => AnyTypeInfoKind::Double, |
| 197 | PgType::Bytea => AnyTypeInfoKind::Blob, |
| 198 | PgType::Text | PgType::Varchar => AnyTypeInfoKind::Text, |
| 199 | PgType::DeclareWithName(UStr::Static("citext")) => AnyTypeInfoKind::Text, |
| 200 | _ => { |
| 201 | return Err(sqlx_core::Error::AnyDriverError( |
| 202 | format!("Any driver does not support the Postgres type {pg_type:?}").into(), |
| 203 | )) |
| 204 | } |
| 205 | }, |
| 206 | }) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | impl<'a> TryFrom<&'a PgColumn> for AnyColumn { |
| 211 | type Error = sqlx_core::Error; |
| 212 | |
| 213 | fn try_from(col: &'a PgColumn) -> Result<Self, Self::Error> { |
| 214 | let type_info = |
| 215 | AnyTypeInfo::try_from(&col.type_info).map_err(|e| sqlx_core::Error::ColumnDecode { |
| 216 | index: col.name.to_string(), |
| 217 | source: e.into(), |
| 218 | })?; |
| 219 | |
| 220 | Ok(AnyColumn { |
| 221 | ordinal: col.ordinal, |
| 222 | name: col.name.clone(), |
| 223 | type_info, |
| 224 | }) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | impl<'a> TryFrom<&'a PgRow> for AnyRow { |
| 229 | type Error = sqlx_core::Error; |
| 230 | |
| 231 | fn try_from(row: &'a PgRow) -> Result<Self, Self::Error> { |
| 232 | AnyRow::map_from(row, row.metadata.column_names.clone()) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | impl<'a> TryFrom<&'a AnyConnectOptions> for PgConnectOptions { |
| 237 | type Error = sqlx_core::Error; |
| 238 | |
| 239 | fn try_from(value: &'a AnyConnectOptions) -> Result<Self, Self::Error> { |
| 240 | let mut opts = PgConnectOptions::parse_from_url(&value.database_url)?; |
| 241 | opts.log_settings = value.log_settings.clone(); |
| 242 | Ok(opts) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | fn map_result(res: PgQueryResult) -> AnyQueryResult { |
| 247 | AnyQueryResult { |
| 248 | rows_affected: res.rows_affected(), |
| 249 | last_insert_id: None, |
| 250 | } |
| 251 | } |