1use crate::{
7 Mssql, MssqlArguments, MssqlColumn, MssqlConnectOptions, MssqlConnection, MssqlQueryResult,
8 MssqlTransactionManager, MssqlType, MssqlTypeInfo,
9};
10use futures_core::future::BoxFuture;
11use futures_core::stream::BoxStream;
12use futures_util::{FutureExt, StreamExt};
13use sqlx_core::any::driver::AnyDriver;
14use sqlx_core::any::{
15 AnyArguments, AnyColumn, AnyConnectOptions, AnyConnectionBackend, AnyQueryResult, AnyRow,
16 AnyStatement, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind,
17};
18use sqlx_core::arguments::Arguments;
19use sqlx_core::column::Column;
20use sqlx_core::connection::{ConnectOptions, Connection};
21use sqlx_core::database::Database;
22use sqlx_core::ext::ustr::UStr;
23use sqlx_core::row::Row;
24use sqlx_core::sql_str::SqlStr;
25use sqlx_core::statement::Statement;
26use sqlx_core::transaction::TransactionManager;
27use sqlx_core::{Either, Error, HashMap};
28use std::sync::Arc;
29
30pub const DRIVER: AnyDriver = AnyDriver::with_migrate::<Mssql>();
32
33impl AnyConnectionBackend for MssqlConnection {
34 fn name(&self) -> &str {
35 <Mssql as Database>::NAME
36 }
37
38 fn close(self: Box<Self>) -> BoxFuture<'static, sqlx_core::Result<()>> {
39 Connection::close(*self).boxed()
40 }
41
42 fn close_hard(self: Box<Self>) -> BoxFuture<'static, sqlx_core::Result<()>> {
43 Connection::close_hard(*self).boxed()
44 }
45
46 fn ping(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
47 Connection::ping(self).boxed()
48 }
49
50 fn begin(&mut self, statement: Option<SqlStr>) -> BoxFuture<'_, sqlx_core::Result<()>> {
51 MssqlTransactionManager::begin(self, statement).boxed()
52 }
53
54 fn commit(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
55 MssqlTransactionManager::commit(self).boxed()
56 }
57
58 fn rollback(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
59 MssqlTransactionManager::rollback(self).boxed()
60 }
61
62 fn start_rollback(&mut self) {
63 MssqlTransactionManager::start_rollback(self);
64 }
65
66 fn get_transaction_depth(&self) -> usize {
67 MssqlTransactionManager::get_transaction_depth(self)
68 }
69
70 fn shrink_buffers(&mut self) {
71 Connection::shrink_buffers(self);
72 }
73
74 fn flush(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
75 Connection::flush(self).boxed()
76 }
77
78 fn should_flush(&self) -> bool {
79 Connection::should_flush(self)
80 }
81
82 #[cfg(feature = "migrate")]
83 fn as_migrate(
84 &mut self,
85 ) -> sqlx_core::Result<&mut (dyn sqlx_core::migrate::Migrate + Send + 'static)> {
86 Ok(self)
87 }
88
89 fn fetch_many(
90 &mut self,
91 query: SqlStr,
92 _persistent: bool,
93 arguments: Option<AnyArguments>,
94 ) -> BoxStream<'_, sqlx_core::Result<Either<AnyQueryResult, AnyRow>>> {
95 let native_arguments = arguments
96 .map(convert_any_arguments)
97 .transpose()
98 .map_err(Error::Encode);
99
100 self.fetch_many_sql(query, native_arguments)
101 .map(|item| match item? {
102 Either::Left(result) => Ok(Either::Left(map_result(result))),
103 Either::Right(row) => {
104 let column_names = column_names(row.columns());
105 AnyRow::map_from(&row, column_names).map(Either::Right)
106 }
107 })
108 .boxed()
109 }
110
111 fn fetch_optional(
112 &mut self,
113 query: SqlStr,
114 _persistent: bool,
115 arguments: Option<AnyArguments>,
116 ) -> BoxFuture<'_, sqlx_core::Result<Option<AnyRow>>> {
117 Box::pin(async move {
118 let native_arguments = arguments
119 .map(convert_any_arguments)
120 .transpose()
121 .map_err(Error::Encode);
122 self.fetch_optional_sql(query, native_arguments)
123 .await?
124 .map(|row| {
125 let column_names = column_names(row.columns());
126 AnyRow::map_from(&row, column_names)
127 })
128 .transpose()
129 })
130 }
131
132 fn prepare_with<'c, 'q: 'c>(
133 &'c mut self,
134 sql: SqlStr,
135 parameters: &[AnyTypeInfo],
136 ) -> BoxFuture<'c, sqlx_core::Result<AnyStatement>> {
137 let parameters = parameters
138 .iter()
139 .map(mssql_type_from_any)
140 .collect::<Result<Vec<_>, _>>();
141
142 Box::pin(async move {
143 let parameters = parameters?;
144 let columns = self.run_prepare(sql.as_str(), ¶meters).await?;
145 let statement = crate::MssqlStatement::with_parameters(
146 sql,
147 columns,
148 if parameters.is_empty() {
149 None
150 } else {
151 Some(Either::Left(parameters))
152 },
153 );
154 let column_names = column_names(statement.columns());
155 AnyStatement::try_from_statement(statement, column_names)
156 })
157 }
158}
159
160fn mssql_type_from_any(type_info: &AnyTypeInfo) -> Result<MssqlTypeInfo, Error> {
161 Ok(match type_info.kind() {
162 AnyTypeInfoKind::Bool => MssqlTypeInfo::BIT,
163 AnyTypeInfoKind::SmallInt => MssqlTypeInfo::SMALLINT,
164 AnyTypeInfoKind::Integer | AnyTypeInfoKind::Null => MssqlTypeInfo::INT,
165 AnyTypeInfoKind::BigInt => MssqlTypeInfo::BIGINT,
166 AnyTypeInfoKind::Real => MssqlTypeInfo::REAL,
167 AnyTypeInfoKind::Double => MssqlTypeInfo::FLOAT,
168 AnyTypeInfoKind::Text => MssqlTypeInfo::NVARCHAR,
169 AnyTypeInfoKind::Blob => MssqlTypeInfo::VARBINARY,
170 })
171}
172
173fn convert_any_arguments(
174 arguments: AnyArguments,
175) -> Result<MssqlArguments, sqlx_core::error::BoxDynError> {
176 let mut out = MssqlArguments::default();
177
178 for argument in arguments.values.0 {
179 match argument {
180 AnyValueKind::Null(AnyTypeInfoKind::Null) => out.add(Option::<i32>::None),
181 AnyValueKind::Null(AnyTypeInfoKind::Bool) => out.add(Option::<bool>::None),
182 AnyValueKind::Null(AnyTypeInfoKind::SmallInt) => out.add(Option::<i16>::None),
183 AnyValueKind::Null(AnyTypeInfoKind::Integer) => out.add(Option::<i32>::None),
184 AnyValueKind::Null(AnyTypeInfoKind::BigInt) => out.add(Option::<i64>::None),
185 AnyValueKind::Null(AnyTypeInfoKind::Real) => out.add(Option::<f32>::None),
186 AnyValueKind::Null(AnyTypeInfoKind::Double) => out.add(Option::<f64>::None),
187 AnyValueKind::Null(AnyTypeInfoKind::Text) => out.add(Option::<String>::None),
188 AnyValueKind::Null(AnyTypeInfoKind::Blob) => out.add(Option::<Vec<u8>>::None),
189 AnyValueKind::Bool(value) => out.add(value),
190 AnyValueKind::SmallInt(value) => out.add(value),
191 AnyValueKind::Integer(value) => out.add(value),
192 AnyValueKind::BigInt(value) => out.add(value),
193 AnyValueKind::Real(value) => out.add(value),
194 AnyValueKind::Double(value) => out.add(value),
195 AnyValueKind::Text(value) => out.add(value.as_str()),
196 AnyValueKind::TextSlice(value) => out.add(value.as_ref()),
197 AnyValueKind::Blob(value) => out.add(value.as_slice()),
198 other => {
199 return Err(format!(
200 "SQL Server Any driver does not support argument value {other:?}"
201 )
202 .into());
203 }
204 }?;
205 }
206
207 Ok(out)
208}
209
210fn map_result(result: MssqlQueryResult) -> AnyQueryResult {
211 AnyQueryResult {
212 rows_affected: result.rows_affected(),
213 last_insert_id: None,
214 }
215}
216
217fn column_names(columns: &[MssqlColumn]) -> Arc<HashMap<UStr, usize>> {
218 Arc::new(
219 columns
220 .iter()
221 .map(|column| (UStr::new(column.name()), column.ordinal()))
222 .collect(),
223 )
224}
225
226impl<'a> TryFrom<&'a AnyConnectOptions> for MssqlConnectOptions {
227 type Error = Error;
228
229 fn try_from(options: &'a AnyConnectOptions) -> Result<Self, Self::Error> {
230 MssqlConnectOptions::from_url(&options.database_url)
231 }
232}
233
234impl<'a> TryFrom<&'a MssqlTypeInfo> for AnyTypeInfo {
235 type Error = Error;
236
237 fn try_from(type_info: &'a MssqlTypeInfo) -> Result<Self, Self::Error> {
238 let kind = match type_info.kind() {
239 MssqlType::Null => AnyTypeInfoKind::Null,
240 MssqlType::Bit => AnyTypeInfoKind::Bool,
241 MssqlType::SmallInt => AnyTypeInfoKind::SmallInt,
242 MssqlType::Int => AnyTypeInfoKind::Integer,
243 MssqlType::BigInt => AnyTypeInfoKind::BigInt,
244 MssqlType::Real => AnyTypeInfoKind::Real,
245 MssqlType::Float => AnyTypeInfoKind::Double,
246 MssqlType::NVarChar | MssqlType::VarChar => AnyTypeInfoKind::Text,
247 MssqlType::VarBinary => AnyTypeInfoKind::Blob,
248 MssqlType::TinyInt
249 | MssqlType::Decimal
250 | MssqlType::Money
251 | MssqlType::Date
252 | MssqlType::Time
253 | MssqlType::DateTime
254 | MssqlType::DateTime2
255 | MssqlType::DateTimeOffset
256 | MssqlType::UniqueIdentifier
257 | MssqlType::Other(_) => {
258 return Err(Error::AnyDriverError(
259 format!("Any driver does not support the SQL Server type {type_info:?}").into(),
260 ));
261 }
262 };
263
264 Ok(AnyTypeInfo { kind })
265 }
266}
267
268impl<'a> TryFrom<&'a MssqlColumn> for AnyColumn {
269 type Error = Error;
270
271 fn try_from(column: &'a MssqlColumn) -> Result<Self, Self::Error> {
272 let type_info =
273 AnyTypeInfo::try_from(column.type_info()).map_err(|error| Error::ColumnDecode {
274 index: column.name().to_owned(),
275 source: error.into(),
276 })?;
277
278 Ok(Self {
279 ordinal: column.ordinal(),
280 name: UStr::new(column.name()),
281 type_info,
282 })
283 }
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 #[test]
291 fn maps_stable_sql_server_types_to_any_types() {
292 assert_eq!(
293 AnyTypeInfo::try_from(&MssqlTypeInfo::BIT).unwrap().kind(),
294 AnyTypeInfoKind::Bool
295 );
296 assert_eq!(
297 AnyTypeInfo::try_from(&MssqlTypeInfo::INT).unwrap().kind(),
298 AnyTypeInfoKind::Integer
299 );
300 assert_eq!(
301 AnyTypeInfo::try_from(&MssqlTypeInfo::NVARCHAR)
302 .unwrap()
303 .kind(),
304 AnyTypeInfoKind::Text
305 );
306 assert_eq!(
307 AnyTypeInfo::try_from(&MssqlTypeInfo::VARCHAR)
308 .unwrap()
309 .kind(),
310 AnyTypeInfoKind::Text
311 );
312 assert_eq!(
313 AnyTypeInfo::try_from(&MssqlTypeInfo::VARBINARY)
314 .unwrap()
315 .kind(),
316 AnyTypeInfoKind::Blob
317 );
318 }
319
320 #[test]
321 fn rejects_unstable_sql_server_types_for_any_mapping() {
322 assert!(matches!(
323 AnyTypeInfo::try_from(&MssqlTypeInfo::TINYINT),
324 Err(Error::AnyDriverError(_))
325 ));
326 }
327}