1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
use std::fmt::Display;
use tiberius::{
error::Error,
time::chrono::{NaiveDate, NaiveDateTime, NaiveTime},
Client, ColumnType, Config,
};
use tokio::net::TcpStream;
use tokio_util::compat::{Compat, TokioAsyncWriteCompatExt};
use regex::Regex;
use serde::{de::DeserializeOwned, Serialize};
pub use tiberius::{EncryptionLevel, Row};
/// Sql(String),会将 String 识别为 sql 语句,而不是参数值
///
/// 仅支持 msget mscount msfind
#[derive(Debug)]
pub struct Sql<T: Into<String>>(pub T);
impl<T: Into<String> + Display> Display for Sql<T> {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(fmt, "Sql({})", self.0)
}
}
// impl<T: Into<String> + Display> From<Sql<T>> for String {
// fn from(value: Sql<T>) -> Self {
// value.0.to_string()
// }
// }
// AsyncRead + AsyncWrite + Unpin + Send
pub struct MssqlQuick {
pub client: Client<Compat<TcpStream>>,
}
impl MssqlQuick {
pub async fn new(url: &str, encryp_level: EncryptionLevel) -> anyhow::Result<MssqlQuick> {
let mut config = Config::from_ado_string(url)?;
config.encryption(encryp_level);
let tcp = TcpStream::connect(config.get_addr()).await?;
tcp.set_nodelay(true)?;
let client = match Client::connect(config, tcp.compat_write()).await {
// Connection successful.
Ok(client) => client,
// The server wants us to redirect to a different address
Err(Error::Routing { host, port }) => {
let mut config = Config::from_ado_string(url)?;
config.host(&host);
config.port(port);
config.encryption(encryp_level);
let tcp = TcpStream::connect(config.get_addr()).await?;
tcp.set_nodelay(true)?;
// we should not have more than one redirect, so we'll short-circuit here.
Client::connect(config, tcp.compat_write()).await?
}
Err(e) => Err(e)?,
};
Ok(MssqlQuick { client })
}
}
/// 运行sql语句,返回想要的结果
pub async fn ms_run_vec<T>(
client: &mut Client<Compat<TcpStream>>,
sql: String,
) -> anyhow::Result<Vec<T>>
where
T: Serialize + DeserializeOwned,
{
let res = client.simple_query(sql).await?.into_results().await?;
if res.len() == 0 {
return Ok(Vec::new());
}
let mut list_str = r#"["#.to_owned();
for row in res[0].iter() {
let columns = row.columns();
let mut item = r#"{"#.to_owned();
for index in 0..columns.len() {
let f_type: ColumnType = columns[index].column_type();
let f_name = columns[index].name();
match f_type {
ColumnType::Null => {
let val: Option<&str> = row.get(f_name);
match val {
Some(_v) => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Bit | ColumnType::Bitn => {
let val: Option<bool> = row.get(f_name);
match val {
Some(v) => {
item += format!(r#""{}":{},"#, f_name, v).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Int1 => {
let val: Option<u8> = row.get(f_name);
match val {
Some(v) => {
item += format!(r#""{}":{},"#, f_name, v).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Int2 => {
let val: Option<i16> = row.get(f_name);
match val {
Some(v) => {
item += format!(r#""{}":{},"#, f_name, v).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Int4 => {
let val: Option<i32> = row.get(f_name);
match val {
Some(v) => {
item += format!(r#""{}":{},"#, f_name, v).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Int8 => {
let val: Option<i64> = row.get(f_name);
match val {
Some(v) => {
item += format!(r#""{}":{},"#, f_name, v).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Intn => {
let row_str = format!(r#"{:?}"#, row);
let re = Regex::new(r"TokenRow \{ data: \[(.*)\] \}, result_index: 0").unwrap();
let caps = re.captures(row_str.as_str()).unwrap();
let re_no = Regex::new(r"\(Some\(.*?\)\),").unwrap();
let no_value = re_no.replace_all(&caps[1], "");
let value: Vec<&str> = no_value.split(" ").collect();
let v_idx = value[index];
let mut val_str = "".to_owned();
if v_idx.contains("I64") {
let val: Option<i64> = row.get(f_name);
val_str = if let Some(v) = val {
format!("{}", v)
} else {
format!("null")
};
} else if v_idx.contains("I32") {
let val: Option<i32> = row.get(f_name);
val_str = if let Some(v) = val {
format!("{}", v)
} else {
format!("null")
};
} else if v_idx.contains("I16") {
let val: Option<i16> = row.get(f_name);
val_str = if let Some(v) = val {
format!("{}", v)
} else {
format!("null")
};
} else if v_idx.contains("U8") {
let val: Option<u8> = row.get(f_name);
val_str = if let Some(v) = val {
format!("{}", v)
} else {
format!("null")
};
}
item += format!(r#""{}":{},"#, f_name, val_str).as_str();
}
ColumnType::Float4 | ColumnType::Money4 => {
let val: Option<f32> = row.get(f_name);
match val {
Some(v) => {
item += format!(r#""{}":{},"#, f_name, v).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Float8
| ColumnType::Money
| ColumnType::Floatn
| ColumnType::Decimaln
| ColumnType::Numericn => {
let val: Option<f64> = row.get(f_name);
match val {
Some(v) => {
item += format!(r#""{}":{},"#, f_name, v).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Datetimen
| ColumnType::Datetime4
| ColumnType::Datetime2
| ColumnType::Datetime
| ColumnType::DatetimeOffsetn => {
let val: Option<NaiveDateTime> = row.get(index);
match val {
Some(v) => {
let date_str = v.to_string();
let v_c = serde_json::to_string(&date_str)?;
item += format!(r#""{}":{},"#, f_name, v_c).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Daten => {
let val: Option<NaiveDate> = row.get(index);
match val {
Some(v) => {
let date_str = v.to_string();
let v_c = serde_json::to_string(&date_str)?;
item += format!(r#""{}":{},"#, f_name, v_c).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
ColumnType::Timen => {
let val: Option<NaiveTime> = row.get(index);
match val {
Some(v) => {
let date_str = v.to_string();
let v_c = serde_json::to_string(&date_str)?;
item += format!(r#""{}":{},"#, f_name, v_c).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
_ => {
let val: Option<&str> = row.get(f_name);
match val {
Some(v) => {
let v_c = serde_json::to_string(&v)?;
item += format!(r#""{}":{},"#, f_name, v_c).as_str();
}
None => {
item += format!(r#""{}":null,"#, f_name).as_str();
}
}
}
}
}
item.pop();
item += "},";
list_str += item.as_str();
}
if res[0].len() > 0 {
list_str.pop();
}
list_str += "]";
let jsonvalue: Vec<T> = serde_json::from_str(list_str.as_str())?;
Ok(jsonvalue)
}