1use std::net::TcpStream;
6use std::thread;
7use std::time::Duration;
8
9use encoding_rs::{Encoding, EUC_KR, GB18030, UTF_8};
10
11use crate::crypto::{compute_session_key, new_client_keypair, SymmCipher, DES_CFB, DH_P_HEX};
12use crate::frame::{
13 CMD_BIND, CMD_EXECUTE, CMD_EXEC_COMPLETE, CMD_FETCH, CMD_HANDSHAKE, CMD_LOGIN,
14 CMD_SESSION_QUERY, Frame, FrameReader,
15};
16use crate::result::{
17 decode_out_value, decode_scalar, encode_date, encode_datetime, encode_datetime2,
18 encode_datetime2_tz, encode_datetime_tz, encode_time, encode_time_tz, parse_cols_robust,
19 parse_columns, parse_rows, parse_rows_param, Column, DmDate, DmDateTime, DmTime, Row, Value,
20 NULL_MARK, DM_BLOB, DM_CLOB,
21};
22use crate::{DmError, Result};
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum OutType {
27 Bool,
28 Int,
29 Float,
30 Str,
31 Date,
32 DateTime,
33}
34
35#[derive(Debug, Clone, PartialEq)]
37pub struct OUT {
38 pub type_hint: Option<OutType>,
39}
40
41impl OUT {
42 pub fn new(type_hint: Option<OutType>) -> Self {
43 OUT { type_hint }
44 }
45}
46
47#[derive(Debug, Clone, PartialEq)]
49pub enum Param {
50 Null,
51 Bool(bool),
52 Int(i64),
54 Float(f64),
55 Str(String),
56 Bytes(Vec<u8>),
57 Date(DmDate),
58 Time(DmTime),
59 DateTime(DmDateTime),
60 Out(Option<OutType>),
62}
63
64impl Param {
65 pub fn out(t: Option<OutType>) -> Param {
66 Param::Out(t)
67 }
68 pub fn is_out(&self) -> bool {
69 matches!(self, Param::Out(_))
70 }
71 pub fn is_null(&self) -> bool {
72 matches!(self, Param::Null)
73 }
74}
75
76#[derive(Debug, Clone, Copy)]
78pub struct ServerParam {
79 pub col_type: i32,
80 pub prec: i32,
81 pub scale: i32,
82 pub io_type: i32,
83}
84
85#[derive(Debug, Clone, PartialEq)]
87pub enum ExecuteResult {
88 Query {
90 columns: Vec<Column>,
91 rows: Vec<Vec<Value>>,
92 },
93 Affected(u64),
95 Call {
97 affected: u64,
98 out: Vec<Value>,
99 },
100}
101
102impl ExecuteResult {
103 pub fn rows(&self) -> Option<&Vec<Vec<Value>>> {
104 match self {
105 ExecuteResult::Query { rows, .. } => Some(rows),
106 _ => None,
107 }
108 }
109 pub fn columns(&self) -> Option<&Vec<Column>> {
110 match self {
111 ExecuteResult::Query { columns, .. } => Some(columns),
112 _ => None,
113 }
114 }
115 pub fn affected(&self) -> Option<u64> {
116 match self {
117 ExecuteResult::Affected(n) | ExecuteResult::Call { affected: n, .. } => Some(*n),
118 _ => None,
119 }
120 }
121}
122
123#[derive(Debug, Clone)]
125pub struct ClientConfig {
126 pub host: String,
127 pub port: u16,
128 pub user: String,
129 pub password: String,
130 pub app_name: String,
131 pub os_name: String,
132 pub timeout: Duration,
134 pub auto_reconnect: bool,
136 pub send_delay: Duration,
139 pub encoding: Option<String>,
143}
144
145impl Default for ClientConfig {
146 fn default() -> Self {
147 ClientConfig {
148 host: "127.0.0.1".into(),
149 port: 5236,
150 user: "SYSDBA".into(),
151 password: String::new(),
152 app_name: "rust-min".into(),
153 os_name: "linux".into(),
154 timeout: Duration::from_secs(15),
155 auto_reconnect: true,
156 send_delay: Duration::ZERO,
159 encoding: None,
160 }
161 }
162}
163
164fn resolve_encoding(name: Option<&str>) -> Option<&'static Encoding> {
166 let s = name?;
167 let s = s.trim();
168 if s.is_empty() {
169 return None;
170 }
171 if s.eq_ignore_ascii_case("utf8") || s.eq_ignore_ascii_case("utf-8") {
172 Some(UTF_8)
173 } else if s.eq_ignore_ascii_case("euckr") || s.eq_ignore_ascii_case("euc-kr") {
174 Some(EUC_KR)
175 } else if s.eq_ignore_ascii_case("gb18030")
176 || s.eq_ignore_ascii_case("gbk")
177 || s.eq_ignore_ascii_case("gb2312")
178 {
179 Some(GB18030)
180 } else {
181 None
182 }
183}
184
185#[derive(Debug, Clone)]
187pub struct LazyState {
188 pub stmt: i32,
189 pub ncols: usize,
190 pub rows_raw: Vec<Row>,
191 pub more: bool,
192 pub closed: bool,
193}
194
195pub struct DmClient {
197 cfg: ClientConfig,
198 reader: Option<FrameReader>,
199 session_key: Option<Vec<u8>>,
200 cipher: Option<SymmCipher>,
201 stmt_id: i32,
203 svr_encoding: &'static Encoding,
205 auto_commit: bool,
206 in_transaction: bool,
208 lob_chunk_size: usize,
210}
211
212impl DmClient {
213 pub fn new(host: &str, port: u16, user: &str, password: &str) -> Self {
214 DmClient::with_config(ClientConfig {
215 host: host.into(),
216 port,
217 user: user.into(),
218 password: password.into(),
219 ..Default::default()
220 })
221 }
222
223 pub fn from_dsn(dsn: &str) -> Result<Self> {
227 let dsn = dsn.trim();
228 let rest = dsn.strip_prefix("dm://").unwrap_or(dsn);
229 let (auth_host, query) = match rest.split_once('?') {
230 Some((a, q)) => (a, Some(q)),
231 None => (rest, None),
232 };
233 let (creds, hostport) = auth_host
235 .rsplit_once('@')
236 .map(|(c, h)| (Some(c), h))
237 .unwrap_or((None, auth_host));
238 let (host, port) = hostport
239 .rsplit_once(':')
240 .map(|(h, p)| (h, p.parse::<u16>().unwrap_or(5236)))
241 .unwrap_or((hostport, 5236));
242 let (user, password) = creds
243 .map(|c| match c.split_once(':') {
244 Some((u, p)) => (u.to_string(), p.to_string()),
245 None => (c.to_string(), String::new()),
246 })
247 .unwrap_or((String::new(), String::new()));
248 let mut cfg = ClientConfig {
249 host: host.to_string(),
250 port,
251 user,
252 password,
253 ..Default::default()
254 };
255 if let Some(q) = query {
256 for pair in q.split('&') {
257 let Some((k, v)) = pair.split_once('=') else { continue };
258 match k.to_ascii_lowercase().as_str() {
259 "encoding" => cfg.encoding = Some(v.to_string()),
260 "timeout" => cfg.timeout = Duration::from_secs(v.parse().unwrap_or(15)),
261 "auto_reconnect" => cfg.auto_reconnect = v.eq_ignore_ascii_case("true") || v == "1",
262 "send_delay_ms" => cfg.send_delay = Duration::from_millis(v.parse().unwrap_or(0)),
263 "app_name" => cfg.app_name = v.to_string(),
264 "os_name" => cfg.os_name = v.to_string(),
265 _ => {}
266 }
267 }
268 }
269 Ok(DmClient::with_config(cfg))
270 }
271
272 pub fn connect_from_dsn(dsn: &str) -> Result<Self> {
274 let mut c = DmClient::from_dsn(dsn)?;
275 c.connect()?;
276 Ok(c)
277 }
278
279 pub fn with_config(cfg: ClientConfig) -> Self {
280 let enc = resolve_encoding(cfg.encoding.as_deref()).unwrap_or(GB18030);
281 DmClient {
282 cfg,
283 reader: None,
284 session_key: None,
285 cipher: None,
286 stmt_id: -1,
287 svr_encoding: enc,
289 auto_commit: true,
290 in_transaction: false,
291 lob_chunk_size: 16000,
292 }
293 }
294
295 pub fn config(&self) -> &ClientConfig {
296 &self.cfg
297 }
298
299 pub fn is_connected(&self) -> bool {
300 self.reader.is_some()
301 }
302
303 pub fn auto_commit(&self) -> bool {
304 self.auto_commit
305 }
306
307 pub fn session_key(&self) -> Option<&[u8]> {
308 self.session_key.as_deref()
309 }
310
311 pub fn server_encoding_name(&self) -> &'static str {
313 self.svr_encoding.name()
314 }
315
316 pub fn set_lob_chunk_size(&mut self, size: usize) {
317 self.lob_chunk_size = size;
318 }
319
320 fn send(&mut self, cmd: i16, opts: &[u8], body: &[u8], stmt: i32) -> Result<()> {
323 let r = self.reader.as_mut().ok_or_else(|| DmError::conn("连接未建立"))?;
324 r.send_frame(stmt, cmd, opts, body)?;
325 if !self.cfg.send_delay.is_zero() {
326 thread::sleep(self.cfg.send_delay);
327 }
328 Ok(())
329 }
330
331 fn read_frame(&mut self) -> Result<Frame> {
332 let r = self.reader.as_mut().ok_or_else(|| DmError::conn("连接未建立"))?;
333 r.read_frame()
334 }
335
336 fn recv(&mut self, expect: i16) -> Result<Frame> {
337 let f = self.read_frame()?;
338 if f.retcode != 0 {
339 return Err(self.server_error(&f));
340 }
341 if f.cmd != expect {
342 return Err(DmError::protocol(format!("期望 cmd={expect},实际 cmd={}", f.cmd)));
343 }
344 Ok(f)
345 }
346
347 fn server_error(&self, f: &Frame) -> DmError {
348 let body = &f.body;
349 let mut msg = self.decode_lossy(body);
350 let start = msg.find(|c: char| !c.is_control()).unwrap_or(0);
353 msg = msg[start..].trim().to_string();
354 DmError::server(f.retcode, msg)
355 }
356
357 fn check_ok(&self, f: &Frame) -> Result<()> {
358 if f.retcode == 0 || f.retcode == 111 || f.retcode == 100 {
359 Ok(())
360 } else {
361 Err(self.server_error(f))
362 }
363 }
364
365 pub fn connect(&mut self) -> Result<()> {
368 let stream = TcpStream::connect((self.cfg.host.as_str(), self.cfg.port))
369 .map_err(|e| DmError::conn(format!("连接 {}:{} 失败: {e}", self.cfg.host, self.cfg.port)))?;
370 stream.set_nodelay(true).ok();
371 stream.set_read_timeout(Some(self.cfg.timeout)).ok();
372 stream.set_write_timeout(Some(self.cfg.timeout)).ok();
373 self.reader = Some(FrameReader::new(stream));
374 self.handshake()?;
375 self.login()?;
376 self.stmt_id = -1; self.auto_commit = true;
378 self.in_transaction = false; Ok(())
380 }
381
382 fn ensure_connection(&mut self) -> Result<()> {
383 if self.reader.is_none() {
384 if self.in_transaction {
385 return Err(DmError::conn(
387 "连接已断开且事务未提交(自动重连已跳过,避免静默丢失事务)",
388 ));
389 }
390 if self.cfg.auto_reconnect {
391 self.connect()?;
392 }
393 }
394 Ok(())
395 }
396
397 fn handshake(&mut self) -> Result<()> {
398 let (priv_x, pub_key) = new_client_keypair();
399 let mut opts = [0u8; 44];
401 opts[..17].copy_from_slice(&[
402 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, ]);
410 let mut body = Vec::with_capacity(81);
411 body.extend_from_slice(&8i32.to_le_bytes()); body.extend_from_slice(b"8.1.5.60");
413 body.push(0);
414 body.extend_from_slice(&64i32.to_le_bytes());
415 body.extend_from_slice(&pub_key);
416
417 self.send(CMD_HANDSHAKE, &opts, &body, 0)?;
418 let resp = self.recv(228)?;
419
420 if self.cfg.encoding.is_none() && resp.opts.len() >= 12 {
424 let code = i32::from_le_bytes(resp.opts[8..12].try_into().unwrap());
425 self.svr_encoding = match code {
426 1 => UTF_8,
427 2 => EUC_KR,
428 _ => GB18030,
429 };
430 }
431
432 let p = parse_bigint_hex(DH_P_HEX);
434 let b = &resp.body;
435 let mut server_pub: Option<Vec<u8>> = None;
436 let mut pos = 0usize;
437 while pos + 4 <= b.len() {
438 let ln = i32::from_le_bytes(b[pos..pos + 4].try_into().unwrap());
439 if ln == 64 && pos + 4 + 64 <= b.len() {
440 let cand = &b[pos + 4..pos + 4 + 64];
441 let val = num_bigint::BigUint::from_bytes_be(cand);
442 if val > num_bigint::BigUint::from(1u32) && val < p {
443 server_pub = Some(cand.to_vec());
444 break;
445 }
446 }
447 pos += 1;
448 }
449 let server_pub = server_pub.ok_or_else(|| {
450 DmError::protocol(format!("握手响应中未找到服务器公钥: {}", hex(&b[..b.len().min(32)])))
451 })?;
452
453 let key = compute_session_key(&priv_x, &server_pub);
455 self.session_key = Some(key.clone());
456 self.cipher = Some(SymmCipher::new(DES_CFB, key));
457 Ok(())
458 }
459
460 fn login(&mut self) -> Result<()> {
461 let mut opts = [0u8; 44];
463 opts[..23].copy_from_slice(&[
464 0x05, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, ]);
475 let cipher = self.cipher.as_ref().ok_or_else(|| DmError::protocol("未握手"))?;
476
477 let mut body = Vec::new();
479 let user_b = self.cfg.user.as_bytes();
480 body.extend_from_slice(&(user_b.len() as i32).to_le_bytes());
481 body.extend_from_slice(&cipher.encrypt(user_b, false)?);
482 let pwd_b = self.cfg.password.as_bytes();
483 body.extend_from_slice(&(pwd_b.len() as i32).to_le_bytes());
484 body.extend_from_slice(&cipher.encrypt(pwd_b, false)?);
485
486 body.extend_from_slice(&0i32.to_le_bytes()); let osb = self.cfg.os_name.as_bytes();
489 body.extend_from_slice(&(osb.len() as i32).to_le_bytes());
490 body.extend_from_slice(osb);
491 body.extend_from_slice(&0i32.to_le_bytes()); body.push(0); body.extend_from_slice(&0u16.to_le_bytes()); self.send(CMD_LOGIN, &opts, &body, 0)?;
496 self.recv(163)?;
497 Ok(())
498 }
499
500 fn session_query(&mut self) -> Result<i32> {
506 self.send(CMD_SESSION_QUERY, &[1, 0, 0, 0], &[], 0)?;
507 let f = self.read_frame()?;
508 if f.retcode != 0 {
509 return Err(self.server_error(&f));
510 }
511 Ok(f.stmt_id)
512 }
513
514 fn execute_opts(&self, has_params: bool) -> [u8; 44] {
517 let auto = if self.auto_commit { 1 } else { 0 };
518 let mut opts = [0u8; 44];
519 opts[0] = auto; opts[1] = if has_params { 0 } else { 1 };
522 opts[3] = 1;
523 opts[7..15].copy_from_slice(&i64::MAX.to_le_bytes()); if !has_params {
525 opts[18] = 1; }
527 opts
528 }
529
530 pub fn execute(&mut self, sql: &str, params: &[Param]) -> Result<ExecuteResult> {
532 self.ensure_connection()?;
533 let stmt = self.session_query()?;
534 let is_query = is_query_sql(sql);
535 let opts = self.execute_opts(!params.is_empty());
536
537 let mut sql_bytes = self.encode_str(sql);
538 sql_bytes.push(0);
539 self.send(CMD_EXECUTE, &opts, &sql_bytes, stmt)?;
540
541 let out_indices: Vec<usize> = params
542 .iter()
543 .enumerate()
544 .filter(|(_, p)| p.is_out())
545 .map(|(i, _)| i)
546 .collect();
547
548 let mut prep_frames: Vec<Frame> = Vec::with_capacity(2);
549 let mut server_params: Option<Vec<ServerParam>> = None;
550 if !params.is_empty() {
551 let f = self.read_frame()?;
553 if f.retcode != 0 && f.retcode != 111 {
554 return Err(self.server_error(&f));
555 }
556 if !is_query && f.cmd == 0 {
557 server_params = Some(parse_server_params(&f.body));
558 }
559 if params.iter().any(|p| lob_len(p, self.svr_encoding) >= 8188) {
561 self.write_lob_params(stmt, server_params.as_deref(), params)?;
562 }
563 self.bind_params(stmt, params, is_query, None, server_params.as_deref())?;
564 prep_frames.push(f);
565 if !is_query {
568 let f13 = self.read_frame()?;
569 if f13.retcode != 0 && f13.retcode != 111 && f13.retcode != 100 {
570 return Err(self.server_error(&f13));
571 }
572 prep_frames.push(f13);
573 self.send(CMD_EXEC_COMPLETE, &[0u8; 44], &[], stmt)?;
574 }
575 }
576
577 let mut frames: Vec<Frame> = prep_frames;
579 for _ in 0..4 {
580 if frames.iter().any(|x| x.cmd == 187) {
582 break;
583 }
584 let f = self.read_frame()?;
585 if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
586 return Err(self.server_error(&f));
587 }
588 let is187 = f.cmd == 187;
589 frames.push(f);
590 if is187 {
591 break;
592 }
593 }
594
595 let mut result: Option<ExecuteResult> = None;
596
597 'outer: for f in &frames {
598 if f.cmd == 187 && f.length > 30 {
599 let ncols = le_u16(&f.opts, 2) as usize;
601 let nrows = le_u16(&f.opts, 4) as usize;
602 if ncols > 0 && ncols <= 1000 {
603 let (cols, pos) = parse_columns(&f.body, 0, ncols, self.svr_encoding)?;
604 let mut rows_raw = parse_rows(&f.body, pos, ncols, nrows)?;
605 if nrows == 0xFFFF {
607 let start_pos = rows_raw.len() as i64;
608 let more = self.fetch_more(stmt, start_pos, ncols)?;
609 rows_raw.extend(more);
610 let _ = self.send(CMD_FETCH, &[], &[], stmt).and_then(|_| self.read_frame());
612 }
613 let rows = self.decode_rows(&cols, &rows_raw, stmt)?;
614 result = Some(ExecuteResult::Query { columns: cols, rows });
615 break 'outer;
616 }
617 } else if f.cmd == 0 && f.length > 30 && !params.is_empty() && is_query {
618 let ncols = le_u16(&f.opts, 4) as usize;
621 if ncols > 0 && ncols <= 1000 {
622 let cols = parse_cols_robust(&f.body, params.len(), ncols, self.svr_encoding)?;
623 for f2 in &frames {
625 if f2.cmd == 187 {
626 let ncols2 = le_u16(&f2.opts, 2) as usize;
627 let nrows2 = le_u16(&f2.opts, 4) as usize;
628 let mut rows_raw: Vec<Row>;
629 if ncols2 > 0 && ncols2 <= 1000 {
630 let (_, pos2) = parse_columns(&f2.body, 0, ncols2, self.svr_encoding)?;
632 rows_raw = parse_rows_param(&f2.body, pos2, ncols2)?;
633 } else {
634 rows_raw = parse_rows_param(&f2.body, 0, ncols)?;
636 }
637 if nrows2 == 0xFFFF {
639 let start_pos = rows_raw.len() as i64;
640 let more = self.fetch_more(stmt, start_pos, ncols)?;
641 rows_raw.extend(more);
642 }
643 let _ = self.send(CMD_FETCH, &[], &[], stmt).and_then(|_| self.read_frame());
645 let rows = self.decode_rows(&cols, &rows_raw, stmt)?;
647 let _ = self.send(CMD_EXEC_COMPLETE, &[0u8; 44], &[], stmt).and_then(|_| self.read_frame());
649 result = Some(ExecuteResult::Query { columns: cols, rows });
650 break 'outer;
651 }
652 }
653 }
654 } else if f.cmd == 187 {
655 let affected = le_i64(&f.opts, 4) as u64;
657 if !out_indices.is_empty() && f.length > 4 {
659 let out = self.parse_out_values(&f.body, &out_indices, server_params.as_deref());
660 if !params.is_empty() && !is_query {
661 let _ = self.read_frame(); }
663 result = Some(ExecuteResult::Call { affected, out });
664 } else {
665 if !params.is_empty() && !is_query {
667 let _ = self.read_frame();
668 }
669 result = Some(ExecuteResult::Affected(affected));
670 }
671 break 'outer;
672 }
673 }
674
675 if params.is_empty() {
677 let _ = self.send(CMD_EXEC_COMPLETE, &[0u8; 44], &[], stmt).and_then(|_| self.read_frame());
678 }
679 result.ok_or_else(|| DmError::protocol("执行未产生有效结果帧"))
680 }
681
682 pub fn execute_lazy(&mut self, sql: &str, params: &[Param]) -> Result<(Vec<Column>, LazyState)> {
685 self.ensure_connection()?;
686 let stmt = self.session_query()?;
687 if !is_query_sql(sql) {
688 return Err(DmError::arg("execute_lazy 仅支持查询"));
689 }
690 let opts = self.execute_opts(true);
691 let mut sql_bytes = self.encode_str(sql);
692 sql_bytes.push(0);
693 self.send(CMD_EXECUTE, &opts, &sql_bytes, stmt)?;
694
695 let prep_frame = self.read_frame()?;
696 if prep_frame.retcode != 0 && prep_frame.retcode != 111 {
697 return Err(self.server_error(&prep_frame));
698 }
699 self.bind_params(stmt, params, true, None, None)?;
700 let ncols = le_u16(&prep_frame.opts, 4) as usize;
701 let cols = parse_cols_robust(&prep_frame.body, params.len(), ncols, self.svr_encoding)?;
702
703 let f = self.read_frame()?;
705 if f.retcode != 0 && f.retcode != 111 {
706 return Err(self.server_error(&f));
707 }
708 let ncols2 = le_u16(&f.opts, 2) as usize;
709 let nrows2 = le_u16(&f.opts, 4) as usize;
710 let rows_raw = if ncols2 > 0 && ncols2 <= 1000 {
711 let (_, pos2) = parse_columns(&f.body, 0, ncols2, self.svr_encoding)?;
712 parse_rows_param(&f.body, pos2, ncols2)?
713 } else {
714 parse_rows_param(&f.body, 0, ncols)?
715 };
716 let more = nrows2 == 0xFFFF;
717 Ok((
718 cols,
719 LazyState { stmt, ncols, rows_raw, more, closed: false },
720 ))
721 }
722
723 pub fn fetch_more(&mut self, stmt: i32, start_pos: i64, ncols: usize) -> Result<Vec<Row>> {
730 const MAX_FETCH_ITERS: u32 = 1_000_000;
731 let mut all: Vec<Row> = Vec::new();
732 let mut start = start_pos;
733 let mut total: i64 = -1; for _ in 0..MAX_FETCH_ITERS {
735 if total > 0 && start >= total {
737 break;
738 }
739 let mut opts = [0u8; 44];
740 opts[..8].copy_from_slice(&start.to_le_bytes());
741 opts[8..16].copy_from_slice(&i64::MAX.to_le_bytes());
742 self.send(7, &opts, &[], stmt)?;
744 let f = self.read_frame()?;
745 if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
746 break;
749 }
750 let t = le_i64(&f.opts, 0);
752 if 0 < t && t < i64::MAX {
753 total = t;
754 }
755 let rows = parse_rows_param(&f.body, 0, ncols)?;
756 let n = rows.len();
757 if n == 0 {
758 break; }
760 start += n as i64;
761 all.extend(rows);
762 }
763 Ok(all)
764 }
765
766 pub fn close_lazy(&mut self, state: &mut LazyState) -> Result<()> {
768 if state.closed {
769 return Ok(());
770 }
771 let stmt = state.stmt;
772 let _ = self.send(CMD_FETCH, &[], &[], stmt).and_then(|_| self.read_frame());
773 let _ = self.send(CMD_EXEC_COMPLETE, &[0u8; 44], &[], stmt).and_then(|_| self.read_frame());
774 state.closed = true;
775 Ok(())
776 }
777
778 pub fn executemany(&mut self, sql: &str, params_list: &[Vec<Param>]) -> Result<u64> {
780 self.ensure_connection()?;
781 let stmt = self.session_query()?;
782 if is_query_sql(sql) {
783 return Err(DmError::arg("executemany 仅支持 DML"));
784 }
785 let opts = self.execute_opts(true);
786 let mut sql_bytes = self.encode_str(sql);
787 sql_bytes.push(0);
788 self.send(CMD_EXECUTE, &opts, &sql_bytes, stmt)?;
789 let prep = self.read_frame()?;
791 if prep.retcode != 0 && prep.retcode != 111 {
792 return Err(self.server_error(&prep));
793 }
794 let server_params = if prep.cmd == 0 {
795 Some(parse_server_params(&prep.body))
796 } else {
797 None
798 };
799 self.bind_params(stmt, ¶ms_list[0], false, Some(params_list), server_params.as_deref())?;
800 let f13 = self.read_frame()?;
802 if f13.retcode != 0 && f13.retcode != 111 && f13.retcode != 100 {
803 return Err(self.server_error(&f13));
804 }
805 self.send(CMD_EXEC_COMPLETE, &[0u8; 44], &[], stmt)?;
806 let mut affected = 0u64;
808 if f13.cmd == 187 {
809 affected = le_u16(&f13.opts, 4) as u64;
810 let _ = self.read_frame(); } else {
812 for _ in 0..4 {
813 let f = self.read_frame()?;
814 if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
815 return Err(self.server_error(&f));
816 }
817 if f.cmd == 187 {
818 affected = le_u16(&f.opts, 4) as u64;
819 let _ = self.read_frame(); break;
821 }
822 }
823 }
824 Ok(affected)
825 }
826
827 pub(crate) fn decode_rows(&mut self, cols: &[Column], rows: &[Row], stmt: i32) -> Result<Vec<Vec<Value>>> {
830 let mut out = Vec::with_capacity(rows.len());
831 for r in rows {
832 let mut v = Vec::with_capacity(r.len());
833 for (i, cell) in r.iter().enumerate() {
834 let val = match cell {
835 None => Value::Null,
836 Some(raw) => {
837 let col = if i < cols.len() { &cols[i] } else { continue; };
838 self.decode_value(raw, col, Some(stmt))?
839 }
840 };
841 v.push(val);
842 }
843 out.push(v);
844 }
845 Ok(out)
846 }
847
848 fn decode_value(&mut self, raw: &[u8], col: &Column, stmt: Option<i32>) -> Result<Value> {
849 if col.col_type == DM_CLOB || col.col_type == DM_BLOB {
850 return self.read_lob(raw, col, stmt);
851 }
852 decode_scalar(raw, col, self.svr_encoding)
853 }
854
855 fn read_lob(&mut self, raw: &[u8], col: &Column, stmt: Option<i32>) -> Result<Value> {
856 if raw.is_empty() {
857 return Ok(if col.col_type == DM_CLOB {
858 Value::Str(String::new())
859 } else {
860 Value::Bytes(Vec::new())
861 });
862 }
863 let data: Vec<u8> = if raw[0] == 0x01 && raw.len() >= 43 {
864 let length = u32::from_le_bytes(raw[9..13].try_into().unwrap()) as usize;
866 raw[43..(43 + length).min(raw.len())].to_vec()
867 } else {
868 self.read_offrow_lob(raw, col, stmt)?
870 };
871 if col.col_type == DM_CLOB {
872 let (s, _, _) = self.svr_encoding.decode(&data);
873 Ok(Value::Str(s.into_owned()))
874 } else {
875 Ok(Value::Bytes(data))
876 }
877 }
878
879 fn read_offrow_lob(&mut self, desc: &[u8], col: &Column, stmt: Option<i32>) -> Result<Vec<u8>> {
880 if desc.len() < 43 {
881 return Ok(Vec::new());
882 }
883 let blob_id = i64::from_le_bytes(desc[1..9].try_into().unwrap());
884 let length = u32::from_le_bytes(desc[9..13].try_into().unwrap()) as i64;
885 let group_id = i16::from_le_bytes(desc[13..15].try_into().unwrap());
886 let file_id = i16::from_le_bytes(desc[15..17].try_into().unwrap());
887 let page_no = i32::from_le_bytes(desc[17..21].try_into().unwrap());
888 let tab_id = i32::from_le_bytes(desc[21..25].try_into().unwrap());
889 let col_id = i16::from_le_bytes(desc[25..27].try_into().unwrap());
890 let row_id = i64::from_le_bytes(desc[27..35].try_into().unwrap());
891 let ex_group = i16::from_le_bytes(desc[35..37].try_into().unwrap());
892 let ex_file = i16::from_le_bytes(desc[37..39].try_into().unwrap());
893 let ex_page = i32::from_le_bytes(desc[39..43].try_into().unwrap());
894
895 let is_clob = col.col_type == DM_CLOB;
896 let lob_flag: u8 = if is_clob { 1 } else { 0 };
897 let mut length = length;
899 let req_unit: i64 = if is_clob { 16000 } else { 32000 };
900 if is_clob {
901 length = self.lob_char_len(
902 lob_flag, blob_id, group_id, file_id, page_no, tab_id, col_id, row_id,
903 ex_group, ex_file, ex_page, stmt,
904 )?;
905 }
906 let mut all: Vec<u8> = Vec::new();
907 let mut offset: i64 = 0;
908 let mut cur_file = file_id;
909 let mut cur_page = page_no;
910 let mut total_offset: i32 = 0;
911 while offset < length {
912 let req = req_unit.min(length - offset);
913 let mut body = Vec::with_capacity(59);
915 body.push(lob_flag);
916 body.extend_from_slice(&tab_id.to_le_bytes());
917 body.extend_from_slice(&col_id.to_le_bytes());
918 body.extend_from_slice(&blob_id.to_le_bytes());
919 body.extend_from_slice(&group_id.to_le_bytes());
920 body.extend_from_slice(&file_id.to_le_bytes());
921 body.extend_from_slice(&page_no.to_le_bytes());
922 body.extend_from_slice(&cur_file.to_le_bytes());
923 body.extend_from_slice(&cur_page.to_le_bytes());
924 body.extend_from_slice(&total_offset.to_le_bytes());
925 body.extend_from_slice(&offset.to_le_bytes());
926 body.extend_from_slice(&req.to_le_bytes());
927 body.extend_from_slice(&row_id.to_le_bytes());
928 body.extend_from_slice(&ex_group.to_le_bytes());
929 body.extend_from_slice(&ex_file.to_le_bytes());
930 body.extend_from_slice(&ex_page.to_le_bytes());
931
932 self.send(32, &[], &body, stmt.unwrap_or(0))?;
933 let f = self.read_frame()?;
934 if f.retcode != 0 && f.retcode != 111 {
935 return Err(self.server_error(&f));
936 }
937 if f.body.len() < 15 {
938 break;
939 }
940 let read_over = f.body[0];
941 let dlen = i32::from_le_bytes(f.body[1..5].try_into().unwrap());
942 if dlen <= 0 {
943 break;
944 }
945 let dlen = dlen as usize;
946 let end = (15 + dlen).min(f.body.len());
947 all.extend_from_slice(&f.body[15..end]);
948 cur_file = i16::from_le_bytes(f.body[5..7].try_into().unwrap());
949 cur_page = i32::from_le_bytes(f.body[7..11].try_into().unwrap());
950 total_offset = i32::from_le_bytes(f.body[11..15].try_into().unwrap());
951 offset += if is_clob { req } else { dlen as i64 };
952 if read_over != 0 {
953 break;
954 }
955 }
956 if is_clob {
957 Ok(all)
958 } else {
959 Ok(all[..(length as usize).min(all.len())].to_vec())
961 }
962 }
963
964 #[allow(clippy::too_many_arguments)] fn lob_char_len(
966 &mut self,
967 lob_flag: u8,
968 blob_id: i64,
969 group_id: i16,
970 file_id: i16,
971 page_no: i32,
972 tab_id: i32,
973 col_id: i16,
974 row_id: i64,
975 ex_group: i16,
976 ex_file: i16,
977 ex_page: i32,
978 stmt: Option<i32>,
979 ) -> Result<i64> {
980 let mut body = Vec::with_capacity(39);
982 body.push(lob_flag);
983 body.extend_from_slice(&blob_id.to_le_bytes());
984 body.extend_from_slice(&group_id.to_le_bytes());
985 body.extend_from_slice(&file_id.to_le_bytes());
986 body.extend_from_slice(&page_no.to_le_bytes());
987 body.extend_from_slice(&tab_id.to_le_bytes());
988 body.extend_from_slice(&col_id.to_le_bytes());
989 body.extend_from_slice(&row_id.to_le_bytes());
990 body.extend_from_slice(&ex_group.to_le_bytes());
991 body.extend_from_slice(&ex_file.to_le_bytes());
992 body.extend_from_slice(&ex_page.to_le_bytes());
993 self.send(29, &[], &body, stmt.unwrap_or(0))?;
994 let f = self.read_frame()?;
995 if f.retcode != 0 && f.retcode != 111 {
996 return Err(self.server_error(&f));
997 }
998 if f.body.len() >= 8 {
999 return Ok(i64::from_le_bytes(f.body[..8].try_into().unwrap()));
1000 }
1001 if f.body.len() >= 4 {
1002 return Ok(i32::from_le_bytes(f.body[..4].try_into().unwrap()) as i64);
1003 }
1004 Ok(0)
1005 }
1006
1007 fn parse_out_values(
1008 &mut self,
1009 body: &[u8],
1010 out_indices: &[usize],
1011 server_params: Option<&[ServerParam]>,
1012 ) -> Vec<Value> {
1013 let mut values = Vec::new();
1014 let mut pos = 0usize;
1015 for &idx in out_indices {
1016 if pos + 2 > body.len() {
1017 values.push(Value::Null);
1018 break;
1019 }
1020 let ln = u16::from_le_bytes(body[pos..pos + 2].try_into().unwrap());
1021 pos += 2;
1022 if ln == NULL_MARK {
1023 values.push(Value::Null);
1024 continue;
1025 }
1026 if pos + ln as usize > body.len() {
1027 values.push(Value::Null);
1028 break;
1029 }
1030 let raw = &body[pos..pos + ln as usize];
1031 pos += ln as usize;
1032 let sp = server_params.and_then(|s| s.get(idx));
1033 let ct = sp.map(|x| x.col_type).unwrap_or(2);
1034 values.push(decode_out_value(raw, ct, self.svr_encoding));
1035 }
1036 values
1037 }
1038
1039 fn bind_params(
1042 &mut self,
1043 stmt: i32,
1044 params: &[Param],
1045 is_query: bool,
1046 batch_list: Option<&[Vec<Param>]>,
1047 server_params: Option<&[ServerParam]>,
1048 ) -> Result<()> {
1049 let groups: Vec<&[Param]> = match batch_list {
1050 Some(bl) => bl.iter().map(|g| g.as_slice()).collect(),
1051 None => vec![params],
1052 };
1053 let first = groups[0];
1054 let n_params = first.len();
1055 let n_batch = groups.len();
1056
1057 let mut opts = [0u8; 44];
1059 opts[0] = if self.auto_commit { 1 } else { 0 };
1060 opts[1..3].copy_from_slice(&(n_params as u16).to_le_bytes());
1061 opts[3] = 1;
1062 opts[4..12].copy_from_slice(&(n_batch as i64).to_le_bytes());
1063 opts[20..28].copy_from_slice(&i64::MAX.to_le_bytes()); opts[28] = 1;
1065 opts[32..36].copy_from_slice(&(-1i32).to_le_bytes()); let mut desc = Vec::with_capacity(n_params * 13);
1069 let mut encoders: Vec<Option<ParamEncoder>> = Vec::with_capacity(n_params);
1070 for (i, p) in first.iter().enumerate() {
1071 if let Param::Out(hint) = p {
1072 let sp = server_params.and_then(|s| s.get(i));
1074 let ct = sp.map(|x| x.col_type).unwrap_or_else(|| out_type_hint(*hint));
1075 let prec = sp.map(|x| x.prec).unwrap_or_else(|| out_type_prec(*hint));
1076 let scale = sp.map(|x| x.scale).unwrap_or(0);
1077 desc.extend_from_slice(&1i8.to_le_bytes());
1078 desc.extend_from_slice(&ct.to_le_bytes());
1079 desc.extend_from_slice(&prec.to_le_bytes());
1080 desc.extend_from_slice(&scale.to_le_bytes());
1081 encoders.push(None);
1082 continue;
1083 }
1084 let is_lob = lob_len(p, self.svr_encoding) >= 8188;
1085 if is_lob {
1086 let ct: i32 = if matches!(p, Param::Str(_)) { 19 } else { 12 };
1088 desc.extend_from_slice(&0i8.to_le_bytes());
1089 desc.extend_from_slice(&ct.to_le_bytes());
1090 desc.extend_from_slice(&0x7FFF_FFFFi32.to_le_bytes());
1091 desc.extend_from_slice(&0i32.to_le_bytes());
1092 encoders.push(Some(ParamEncoder::from_type(ct)));
1093 } else if let Some(sp) = server_params.and_then(|s| s.get(i)) {
1094 desc.extend_from_slice(&0i8.to_le_bytes());
1095 desc.extend_from_slice(&sp.col_type.to_le_bytes());
1096 desc.extend_from_slice(&sp.prec.to_le_bytes());
1097 desc.extend_from_slice(&sp.scale.to_le_bytes());
1098 encoders.push(Some(ParamEncoder::from_type(sp.col_type)));
1099 } else {
1100 let (ct, prec, scale, enc) = param_type(p, is_query, self.svr_encoding);
1101 desc.extend_from_slice(&0i8.to_le_bytes());
1102 desc.extend_from_slice(&ct.to_le_bytes());
1103 desc.extend_from_slice(&prec.to_le_bytes());
1104 desc.extend_from_slice(&scale.to_le_bytes());
1105 encoders.push(Some(enc));
1106 }
1107 }
1108
1109 let mut data = Vec::new();
1111 for group in &groups {
1112 for (i, p) in group.iter().enumerate() {
1113 if p.is_out() {
1114 continue; }
1116 if p.is_null() {
1117 data.extend_from_slice(&NULL_MARK.to_le_bytes());
1118 } else {
1119 let enc = encoders
1120 .get(i)
1121 .and_then(|e| e.clone())
1122 .unwrap_or_else(|| param_type(p, is_query, self.svr_encoding).3);
1123 let raw = enc.encode(p, self.svr_encoding)?;
1124 if lob_len(p, self.svr_encoding) >= 8188 {
1125 data.extend_from_slice(&0u16.to_le_bytes()); } else {
1127 data.extend_from_slice(&(raw.len() as u16).to_le_bytes());
1128 data.extend_from_slice(&raw);
1129 }
1130 }
1131 }
1132 }
1133
1134 let mut body = desc;
1135 body.extend_from_slice(&data);
1136 self.send(CMD_BIND, &opts, &body, stmt)?;
1137 Ok(())
1138 }
1139
1140 fn write_lob_params(
1141 &mut self,
1142 stmt: i32,
1143 server_params: Option<&[ServerParam]>,
1144 params: &[Param],
1145 ) -> Result<()> {
1146 let mut desc = Vec::new();
1148 for (i, p) in params.iter().enumerate() {
1149 let raw_len = lob_len(p, self.svr_encoding);
1150 if raw_len >= 8188 {
1151 let ct: i32 = if matches!(p, Param::Str(_)) { 19 } else { 12 };
1152 desc.extend_from_slice(&0i8.to_le_bytes());
1153 desc.extend_from_slice(&ct.to_le_bytes());
1154 desc.extend_from_slice(&0x7FFF_FFFFi32.to_le_bytes());
1155 desc.extend_from_slice(&0i32.to_le_bytes());
1156 } else {
1157 let sp = server_params.and_then(|s| s.get(i));
1158 let ct = sp.map(|x| x.col_type).unwrap_or(2);
1159 let prec = sp.map(|x| x.prec).unwrap_or(0);
1160 let scale = sp.map(|x| x.scale).unwrap_or(0);
1161 desc.extend_from_slice(&0i8.to_le_bytes());
1162 desc.extend_from_slice(&ct.to_le_bytes());
1163 desc.extend_from_slice(&prec.to_le_bytes());
1164 desc.extend_from_slice(&scale.to_le_bytes());
1165 }
1166 }
1167 let mut opts90 = [0u8; 44];
1169 opts90[..2].copy_from_slice(&(params.len() as u16).to_le_bytes());
1170 self.send(90, &opts90, &desc, stmt)?;
1171 let f = self.read_frame()?;
1172 if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
1173 return Err(self.server_error(&f));
1174 }
1175 for (i, p) in params.iter().enumerate() {
1177 if lob_len(p, self.svr_encoding) < 8188 {
1178 continue;
1179 }
1180 let data: Vec<u8> = match p {
1181 Param::Str(s) => self.encode_str(s),
1182 Param::Bytes(b) => b.clone(),
1183 _ => Vec::new(),
1184 };
1185 let mut opts14 = [0u8; 44];
1186 opts14[0] = i as u8; let mut off = 0;
1188 while off < data.len() {
1189 let mut end = (off + self.lob_chunk_size).min(data.len());
1190 if self.svr_encoding == GB18030 || self.svr_encoding == EUC_KR {
1194 while end < data.len() && end > off
1195 && (0x81..=0xFE).contains(&data[end - 1])
1196 && (0x40..=0xFE).contains(&data[end])
1197 && data[end] != 0x7F
1198 {
1199 end -= 1;
1200 }
1201 } else {
1202 while end < data.len() && end > off && (0x80..=0xBF).contains(&data[end]) {
1203 end -= 1;
1204 }
1205 }
1206 let chunk = &data[off..end];
1207 let mut body = Vec::with_capacity(8 + chunk.len());
1208 body.extend_from_slice(&(chunk.len() as i32).to_le_bytes());
1209 body.extend_from_slice(&(-1i32).to_le_bytes());
1210 body.extend_from_slice(chunk);
1211 self.send(14, &opts14, &body, stmt)?;
1212 let f = self.read_frame()?;
1213 if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
1214 return Err(self.server_error(&f));
1215 }
1216 off = end;
1217 }
1218 }
1219 Ok(())
1220 }
1221
1222 pub fn begin(&mut self) -> Result<()> {
1226 self.send(52, &1i32.to_le_bytes(), &[], 0)?;
1227 let f = self.read_frame()?;
1228 self.check_ok(&f)?;
1229 self.auto_commit = false;
1230 self.in_transaction = true;
1231 Ok(())
1232 }
1233
1234 pub fn commit(&mut self) -> Result<()> {
1236 self.send(8, &[], &[], 0)?;
1237 let f = self.read_frame()?;
1238 self.check_ok(&f)?;
1239 self.auto_commit = true;
1240 self.in_transaction = false;
1241 Ok(())
1242 }
1243
1244 pub fn rollback(&mut self) -> Result<()> {
1246 self.send(9, &[], &[], 0)?;
1247 let f = self.read_frame()?;
1248 self.check_ok(&f)?;
1249 self.auto_commit = true;
1250 self.in_transaction = false;
1251 Ok(())
1252 }
1253
1254 pub fn set_iso_level(&mut self, level: i32) -> Result<()> {
1256 self.send(52, &level.to_le_bytes(), &[], 0)?;
1257 let f = self.read_frame()?;
1258 self.check_ok(&f)?;
1259 Ok(())
1260 }
1261
1262 pub fn close(&mut self) {
1263 self.reader = None;
1264 }
1265
1266 fn encode_str(&self, s: &str) -> Vec<u8> {
1268 enc_str(self.svr_encoding, s)
1269 }
1270
1271 fn decode_lossy(&self, b: &[u8]) -> String {
1273 let (s, _, _) = self.svr_encoding.decode(b);
1274 s.into_owned()
1275 }
1276}
1277
1278pub(crate) fn is_query_sql(sql: &str) -> bool {
1281 let s = sql.trim_start();
1282 let up = s.to_ascii_uppercase();
1283 up.starts_with("SELECT")
1284 || up.starts_with("WITH")
1285 || up.starts_with("DESC")
1286 || up.starts_with("SHOW")
1287}
1288
1289pub(crate) fn enc_str(enc: &'static Encoding, s: &str) -> Vec<u8> {
1291 enc.encode(s).0.into_owned()
1292}
1293
1294fn apply_exp(mant: &str, exp: i64) -> String {
1296 if exp == 0 {
1297 return mant.to_string();
1298 }
1299 let neg = mant.starts_with('-');
1300 let m = mant.trim_start_matches(['-', '+']);
1301 let digits: String = m.replace(".", "");
1302 let int_len = m.find('.').map(|i| i as i64).unwrap_or(digits.len() as i64) + exp;
1303 let mut out = if int_len <= 0 {
1304 format!("0.{}{}", "0".repeat((-int_len) as usize), digits)
1305 } else if int_len >= digits.len() as i64 {
1306 format!("{}{}", digits, "0".repeat((int_len - digits.len() as i64) as usize))
1307 } else {
1308 let p = int_len as usize;
1309 format!("{}.{}", &digits[..p], &digits[p..])
1310 };
1311 if neg {
1312 out.insert(0, '-');
1313 }
1314 out
1315}
1316
1317pub(crate) fn enc_decimal(s: &str) -> Vec<u8> {
1320 let s = s.trim();
1321 if s.is_empty() || s == "0" {
1322 return vec![0x80];
1323 }
1324 let (neg, body) = if let Some(r) = s.strip_prefix('-') {
1325 (true, r)
1326 } else {
1327 (false, s.strip_prefix('+').unwrap_or(s))
1328 };
1329 let body = match body.find(['e', 'E']) {
1331 Some(ci) => {
1332 let (mant, exp) = (&body[..ci], &body[ci + 1..]);
1333 apply_exp(mant, exp.parse::<i64>().unwrap_or(0))
1334 }
1335 None => body.to_string(),
1336 };
1337 let (mut weight, mut digits) = if let Some(pi) = body.find('.') {
1339 let intp = body[..pi].to_string();
1340 let frac = body[pi + 1..].to_string();
1341 if intp.chars().all(|c| c == '0') {
1342 let first = frac.find(|c| c != '0').unwrap_or(frac.len());
1343 (-(first as i64 + (frac.len() - first) as i64), frac[first..].to_string())
1344 } else {
1345 (-(frac.len() as i64), format!("{intp}{frac}"))
1346 }
1347 } else {
1348 (0i64, body.clone())
1349 };
1350 while digits.ends_with('0') && digits.len() > 1 {
1352 digits.pop();
1353 weight += 1;
1354 }
1355 if digits.chars().all(|c| c == '0') {
1357 return vec![0x80];
1358 }
1359 if weight % 2 != 0 {
1361 digits.push('0');
1362 weight -= 1;
1363 }
1364 if digits.len() % 2 != 0 {
1365 digits.insert(0, '0');
1366 }
1367 let exp = (weight + digits.len() as i64) / 2 - 1;
1369 let exp_max = if neg { 61 } else { 62 };
1370 if exp > exp_max || exp < -62 {
1371 return Vec::new(); }
1373 let mut valid_len = digits.len() / 2 + 1;
1374 if neg && valid_len >= 21 {
1375 valid_len = 20;
1376 } else if valid_len > 21 {
1377 valid_len = 21;
1378 }
1379 let ret_len = if neg { valid_len + 1 } else { valid_len };
1380 let mut out = vec![0u8; ret_len];
1381 out[0] = if neg { (0x3E - exp as i32) as u8 } else { (exp as i32 + 0xC1) as u8 };
1382 let mut ib = 1usize;
1383 let mut k = 0usize;
1384 while ib < valid_len && k + 2 <= digits.len() {
1385 if let Ok(d) = digits[k..k + 2].parse::<u8>() {
1386 out[ib] = if neg { 101 - d } else { d + 1 };
1387 }
1388 ib += 1;
1389 k += 2;
1390 }
1391 if neg && ib < ret_len {
1392 out[ib] = 0x66;
1393 ib += 1;
1394 }
1395 if ib < ret_len {
1396 out[ib] = 0x00;
1397 }
1398 out
1399}
1400
1401pub(crate) fn lob_len(p: &Param, enc: &'static Encoding) -> usize {
1403 match p {
1404 Param::Str(s) => enc_str(enc, s).len(),
1405 Param::Bytes(b) => b.len(),
1406 _ => 0,
1407 }
1408}
1409
1410fn param_type(p: &Param, is_query: bool, enc: &'static Encoding) -> (i32, i32, i32, ParamEncoder) {
1415 match p {
1416 Param::Bool(_) => (7, 4, 0, ParamEncoder::Int),
1417 Param::Int(_) => {
1418 if is_query {
1420 (8, 8, 0, ParamEncoder::BigInt)
1421 } else {
1422 (7, 4, 0, ParamEncoder::Int)
1423 }
1424 }
1425 Param::Float(_) => (11, 8, 0, ParamEncoder::Double),
1426 Param::Date(_) => (14, 3, 0, ParamEncoder::Date),
1427 Param::DateTime(dt) => {
1428 if dt.time.timezone_minutes.is_some() {
1429 (23, 8, 0, ParamEncoder::DateTimeTz)
1430 } else {
1431 (16, 8, 0, ParamEncoder::DateTime)
1432 }
1433 }
1434 Param::Time(t) => {
1435 if t.timezone_minutes.is_some() {
1436 (22, 5, 0, ParamEncoder::TimeTz)
1437 } else {
1438 (15, 5, 0, ParamEncoder::Time)
1439 }
1440 }
1441 Param::Bytes(b) => (17, b.len() as i32, 0, ParamEncoder::Bytes),
1442 Param::Str(s) => {
1443 let len = enc_str(enc, s).len();
1444 let prec = if is_query { 8188 } else { 50.max(len as i32) };
1446 (2, prec, 0, ParamEncoder::Str)
1447 }
1448 Param::Null => {
1449 (2, 8188, 0, ParamEncoder::Str)
1451 }
1452 Param::Out(_) => (2, 0, 0, ParamEncoder::Str),
1453 }
1454}
1455
1456fn out_type_hint(hint: Option<OutType>) -> i32 {
1457 match hint {
1458 Some(OutType::Bool) => 13,
1459 Some(OutType::Int) => 8,
1460 Some(OutType::Float) => 11,
1461 Some(OutType::Str) => 2,
1462 Some(OutType::Date) => 14,
1463 Some(OutType::DateTime) => 16,
1464 None => 2,
1465 }
1466}
1467
1468fn out_type_prec(hint: Option<OutType>) -> i32 {
1469 match hint {
1470 Some(OutType::Int) => 8,
1471 Some(OutType::Str) => 32767,
1472 Some(OutType::DateTime) => 8,
1473 Some(OutType::Date) => 3,
1474 _ => 8,
1475 }
1476}
1477
1478pub fn parse_server_params(body: &[u8]) -> Vec<ServerParam> {
1480 let mut params = Vec::new();
1481 let n = body.len();
1482 let mut pos = 0usize;
1483 while pos + 31 <= n {
1484 let col_type = le_i32(body, pos);
1485 let prec = le_i32(body, pos + 4);
1486 let scale = le_i32(body, pos + 8);
1487 pos += 16;
1488 if pos + 2 > n {
1489 break;
1490 }
1491 pos += 2; pos += 4; if pos + 2 > n {
1494 break;
1495 }
1496 let io_type = body[pos] as i32;
1497 pos += 2; if pos + 8 > n {
1499 break;
1500 }
1501 let nlen = i16::from_le_bytes(body[pos..pos + 2].try_into().unwrap());
1502 let tlen = i16::from_le_bytes(body[pos + 2..pos + 4].try_into().unwrap());
1503 let tblen = i16::from_le_bytes(body[pos + 4..pos + 6].try_into().unwrap());
1504 let slen = i16::from_le_bytes(body[pos + 6..pos + 8].try_into().unwrap());
1505 pos += 8;
1506 let total = (nlen + tlen + tblen + slen) as i64;
1507 if pos + total as usize > n {
1508 break;
1509 }
1510 pos += total as usize;
1511 params.push(ServerParam { col_type, prec, scale, io_type });
1512 if !(0..=40).contains(&col_type) {
1514 break;
1515 }
1516 }
1517 params
1518}
1519
1520#[derive(Debug, Clone, PartialEq)]
1522enum ParamEncoder {
1523 Str,
1524 Decimal,
1525 TinyInt,
1526 SmallInt,
1527 Int,
1528 BigInt,
1529 Real,
1530 Double,
1531 Bool,
1532 Date,
1533 Time,
1534 TimeTz,
1535 DateTime,
1536 DateTimeTz,
1537 DateTime2,
1538 DateTime2Tz,
1539 Bytes,
1540}
1541
1542impl ParamEncoder {
1543 fn from_type(col_type: i32) -> Self {
1544 match col_type {
1545 0 | 1 | 2 | 19 => ParamEncoder::Str, 9 => ParamEncoder::Decimal, 5 => ParamEncoder::TinyInt,
1548 6 => ParamEncoder::SmallInt,
1549 7 => ParamEncoder::Int,
1550 8 => ParamEncoder::BigInt,
1551 10 => ParamEncoder::Real,
1552 11 => ParamEncoder::Double,
1553 13 => ParamEncoder::Bool,
1554 14 => ParamEncoder::Date,
1555 15 => ParamEncoder::Time,
1556 22 => ParamEncoder::TimeTz, 16 => ParamEncoder::DateTime,
1558 23 => ParamEncoder::DateTimeTz, 26 => ParamEncoder::DateTime2, 27 => ParamEncoder::DateTime2Tz, 12 | 17 | 18 => ParamEncoder::Bytes, _ => ParamEncoder::Str,
1563 }
1564 }
1565
1566 fn encode(&self, p: &Param, enc: &'static Encoding) -> Result<Vec<u8>> {
1567 match self {
1568 ParamEncoder::Str => match p {
1569 Param::Str(s) => Ok(enc_str(enc, s)),
1570 Param::Bytes(b) => Ok(b.clone()),
1571 _ => Ok(enc_str(enc, &to_string_value(p))),
1572 },
1573 ParamEncoder::Decimal => Ok(enc_decimal(&to_string_value(p))),
1574 ParamEncoder::TinyInt => Ok((to_i64(p)? as i8).to_le_bytes().to_vec()),
1575 ParamEncoder::SmallInt => Ok((to_i64(p)? as i16).to_le_bytes().to_vec()),
1576 ParamEncoder::Int => Ok((to_i64(p)? as i32).to_le_bytes().to_vec()),
1577 ParamEncoder::BigInt => Ok(to_i64(p)?.to_le_bytes().to_vec()),
1578 ParamEncoder::Real => Ok((to_f64(p)? as f32).to_le_bytes().to_vec()),
1579 ParamEncoder::Double => Ok(to_f64(p)?.to_le_bytes().to_vec()),
1580 ParamEncoder::Bool => Ok(vec![if to_bool(p) { 1 } else { 0 }]),
1581 ParamEncoder::Date => Ok(encode_date(&to_date(p)?).to_vec()),
1582 ParamEncoder::Time => Ok(encode_time(&to_time(p)?).to_vec()),
1583 ParamEncoder::TimeTz => Ok(encode_time_tz(&to_time(p)?)),
1584 ParamEncoder::DateTime => Ok(encode_datetime(&to_datetime(p)?)),
1585 ParamEncoder::DateTimeTz => Ok(encode_datetime_tz(&to_datetime(p)?)),
1586 ParamEncoder::DateTime2 => Ok(encode_datetime2(&to_datetime(p)?)),
1587 ParamEncoder::DateTime2Tz => Ok(encode_datetime2_tz(&to_datetime(p)?)),
1588 ParamEncoder::Bytes => match p {
1589 Param::Bytes(b) => Ok(b.clone()),
1590 _ => Ok(to_string_value(p).into_bytes()),
1591 },
1592 }
1593 }
1594}
1595
1596fn to_i64(p: &Param) -> Result<i64> {
1597 match p {
1598 Param::Int(v) => Ok(*v),
1599 Param::Bool(b) => Ok(*b as i64),
1600 Param::Float(f) => Ok(*f as i64),
1601 Param::Str(s) => s.trim().parse::<i64>().map_err(|_| DmError::arg(format!("无法将 '{s}' 转为整数"))),
1602 Param::Null => Ok(0),
1603 _ => Err(DmError::arg(format!("无法将 {p:?} 转为整数"))),
1604 }
1605}
1606
1607fn to_f64(p: &Param) -> Result<f64> {
1608 match p {
1609 Param::Float(f) => Ok(*f),
1610 Param::Int(v) => Ok(*v as f64),
1611 Param::Bool(b) => Ok((*b as i64) as f64),
1612 Param::Str(s) => s.trim().parse::<f64>().map_err(|_| DmError::arg(format!("无法将 '{s}' 转为浮点"))),
1613 _ => Err(DmError::arg(format!("无法将 {p:?} 转为浮点"))),
1614 }
1615}
1616
1617fn to_bool(p: &Param) -> bool {
1618 match p {
1619 Param::Bool(b) => *b,
1620 Param::Int(v) => *v != 0,
1621 Param::Float(f) => *f != 0.0,
1622 Param::Str(s) => !s.is_empty() && s != "0" && !s.eq_ignore_ascii_case("false"),
1623 _ => false,
1624 }
1625}
1626
1627fn to_date(p: &Param) -> Result<DmDate> {
1628 match p {
1629 Param::Date(d) => Ok(*d),
1630 Param::DateTime(dt) => Ok(dt.date),
1631 Param::Str(s) => parse_date_str(s),
1632 _ => Err(DmError::arg(format!("无法将 {p:?} 转为日期"))),
1633 }
1634}
1635
1636fn to_time(p: &Param) -> Result<DmTime> {
1637 match p {
1638 Param::Time(t) => Ok(*t),
1639 Param::DateTime(dt) => Ok(dt.time),
1640 Param::Str(s) => parse_time_str(s),
1641 _ => Err(DmError::arg(format!("无法将 {p:?} 转为时间"))),
1642 }
1643}
1644
1645fn to_datetime(p: &Param) -> Result<DmDateTime> {
1646 match p {
1647 Param::DateTime(dt) => Ok(*dt),
1648 Param::Date(d) => Ok(DmDateTime::new(*d, DmTime::new(0, 0, 0, 0))),
1649 Param::Str(s) => {
1650 let d = parse_date_str(&s[..s.len().min(10)])?;
1652 let t = if s.len() > 10 {
1653 parse_time_str(&s[11..])?
1654 } else {
1655 DmTime::new(0, 0, 0, 0)
1656 };
1657 Ok(DmDateTime::new(d, t))
1658 }
1659 _ => Err(DmError::arg(format!("无法将 {p:?} 转为日期时间"))),
1660 }
1661}
1662
1663fn to_string_value(p: &Param) -> String {
1664 match p {
1665 Param::Str(s) => s.clone(),
1666 Param::Int(v) => v.to_string(),
1667 Param::Float(f) => f.to_string(),
1668 Param::Bool(b) => b.to_string(),
1669 Param::Date(d) => d.to_string(),
1670 Param::Time(t) => t.to_string(),
1671 Param::DateTime(dt) => dt.to_string(),
1672 Param::Bytes(b) => String::from_utf8_lossy(b).into_owned(),
1673 Param::Null => "".to_string(),
1674 Param::Out(_) => "".to_string(),
1675 }
1676}
1677
1678fn parse_date_str(s: &str) -> Result<DmDate> {
1680 let parts: Vec<&str> = s.trim().split('-').collect();
1681 if parts.len() != 3 {
1682 return Err(DmError::arg(format!("日期格式错误: '{s}'")));
1683 }
1684 let year: i32 = parts[0].parse().map_err(|_| DmError::arg(format!("日期格式错误: '{s}'")))?;
1685 let month: u8 = parts[1].parse().map_err(|_| DmError::arg(format!("日期格式错误: '{s}'")))?;
1686 let day: u8 = parts[2].parse().map_err(|_| DmError::arg(format!("日期格式错误: '{s}'")))?;
1687 Ok(DmDate::new(year, month, day))
1688}
1689
1690fn parse_time_str(s: &str) -> Result<DmTime> {
1692 let s = s.trim();
1693 let (hms, frac) = match s.split_once('.') {
1694 Some((h, f)) => (h, Some(f)),
1695 None => (s, None),
1696 };
1697 let parts: Vec<&str> = hms.split(':').collect();
1698 if parts.len() < 2 {
1699 return Err(DmError::arg(format!("时间格式错误: '{s}'")));
1700 }
1701 let hour: u8 = parts[0].parse().map_err(|_| DmError::arg(format!("时间格式错误: '{s}'")))?;
1702 let minute: u8 = parts[1].parse().map_err(|_| DmError::arg(format!("时间格式错误: '{s}'")))?;
1703 let second: u8 = if parts.len() > 2 { parts[2].parse().map_err(|_| DmError::arg(format!("时间格式错误: '{s}'")))? } else { 0 };
1704 let microsecond: u32 = match frac {
1705 Some(f) => {
1706 let mut f = f.to_string();
1707 while f.len() < 6 {
1708 f.push('0');
1709 }
1710 f[..6].parse().unwrap_or(0)
1711 }
1712 None => 0,
1713 };
1714 Ok(DmTime::new(hour, minute, second, microsecond))
1715}
1716
1717fn le_i32(b: &[u8], pos: usize) -> i32 {
1718 i32::from_le_bytes(b[pos..pos + 4].try_into().unwrap())
1719}
1720
1721fn le_u16(b: &[u8], pos: usize) -> u16 {
1722 u16::from_le_bytes(b[pos..pos + 2].try_into().unwrap())
1723}
1724
1725fn le_i64(b: &[u8], pos: usize) -> i64 {
1726 i64::from_le_bytes(b[pos..pos + 8].try_into().unwrap())
1727}
1728
1729fn parse_bigint_hex(hex: &str) -> num_bigint::BigUint {
1730 num_bigint::BigUint::parse_bytes(hex.as_bytes(), 16).expect("hex 解析失败")
1731}
1732
1733fn hex(b: &[u8]) -> String {
1734 b.iter().map(|x| format!("{x:02x}")).collect()
1735}
1736
1737#[cfg(test)]
1738mod tests {
1739 use super::*;
1740
1741 #[test]
1742 fn decimal_encoder_binds_dec_column() {
1743 assert!(matches!(ParamEncoder::from_type(9), ParamEncoder::Decimal));
1745 let enc = ParamEncoder::Decimal;
1746 assert_eq!(enc.encode(&Param::Float(1.5), encoding_rs::GB18030).unwrap(), vec![0xC1, 0x02, 0x33]);
1747 assert_eq!(enc.encode(&Param::Str("1.50".into()), encoding_rs::GB18030).unwrap(), vec![0xC1, 0x02, 0x33]);
1748 assert_eq!(enc.encode(&Param::Int(1), encoding_rs::GB18030).unwrap(), vec![0xC1, 0x02]);
1749 }
1750
1751 #[test]
1752 fn is_query_detection() {
1753 assert!(is_query_sql(" SELECT * FROM t"));
1754 assert!(is_query_sql("WITH x AS (...) SELECT 1"));
1755 assert!(is_query_sql("DESC t"));
1756 assert!(is_query_sql("SHOW TABLES"));
1757 assert!(!is_query_sql("INSERT INTO t VALUES (1)"));
1758 assert!(!is_query_sql("CALL proc(1)"));
1759 assert!(!is_query_sql("UPDATE t SET a=1"));
1760 }
1761
1762 #[test]
1763 fn param_type_guess() {
1764 let (ct, prec, scale, enc) = param_type(&Param::Int(1), true, GB18030);
1765 assert_eq!((ct, prec, scale), (8, 8, 0));
1766 assert_eq!(enc.encode(&Param::Int(1), GB18030).unwrap(), 1i64.to_le_bytes());
1767
1768 let (ct, prec, scale, _) = param_type(&Param::Int(1), false, GB18030);
1769 assert_eq!((ct, prec, scale), (7, 4, 0));
1770
1771 let (ct, prec, _, _) = param_type(&Param::Str("测试".into()), false, GB18030);
1772 assert_eq!(ct, 2);
1773 assert_eq!(prec, 50); let (ct, prec, _, _) = param_type(&Param::Str("测试".into()), false, UTF_8);
1777 assert_eq!(ct, 2);
1778 assert_eq!(prec, 50);
1779
1780 let s = "中".repeat(30); let (_ct, prec, _, _) = param_type(&Param::Str(s.clone()), false, UTF_8);
1783 assert_eq!(prec, 90);
1784 let (_ct, prec, _, _) = param_type(&Param::Str(s.clone()), false, GB18030);
1785 assert_eq!(prec, 60); let (_ct, prec, _, _) = param_type(&Param::Str("x".repeat(100).as_str().into()), false, GB18030);
1788 assert_eq!(prec, 100);
1789
1790 let (ct, prec, _, _) = param_type(&Param::Str("x".into()), true, GB18030);
1791 assert_eq!(ct, 2);
1792 assert_eq!(prec, 8188);
1793
1794 let mut tt = DmTime::new(12, 34, 56, 0);
1796 tt.timezone_minutes = Some(480);
1797 let (ct, prec, scale, enc) = param_type(&Param::Time(tt), false, GB18030);
1798 assert_eq!((ct, prec, scale), (22, 5, 0));
1799 assert_eq!(enc.encode(&Param::Time(tt), GB18030).unwrap(), encode_time_tz(&tt));
1800
1801 let mut dtz = DmDateTime::new(DmDate::new(2026, 8, 14), DmTime::new(12, 34, 56, 0));
1802 dtz.time.timezone_minutes = Some(480);
1803 let (ct, prec, scale, enc) = param_type(&Param::DateTime(dtz), false, GB18030);
1804 assert_eq!((ct, prec, scale), (23, 8, 0));
1805 assert_eq!(enc.encode(&Param::DateTime(dtz), GB18030).unwrap(), encode_datetime_tz(&dtz));
1806
1807 let (ct, _, _, _) = param_type(&Param::Time(DmTime::new(1, 2, 3, 0)), false, GB18030);
1809 assert_eq!(ct, 15);
1810 let (ct, _, _, _) = param_type(&Param::DateTime(DmDateTime::new(DmDate::new(2026, 1, 1), DmTime::new(0, 0, 0, 0))), false, GB18030);
1811 assert_eq!(ct, 16);
1812 let (ct, _, _, _) = param_type(&Param::Date(DmDate::new(2026, 8, 12)), false, GB18030);
1813 assert_eq!(ct, 14);
1814 let (ct, _, _, _) = param_type(&Param::Float(1.5), false, GB18030);
1815 assert_eq!(ct, 11);
1816 let (ct, _, _, _) = param_type(&Param::Bytes(vec![1, 2]), false, GB18030);
1817 assert_eq!(ct, 17);
1818 let (ct, _, _, _) = param_type(&Param::Bool(true), false, GB18030);
1819 assert_eq!(ct, 7);
1820 let (ct, _, _, _) = param_type(&Param::Null, false, GB18030);
1821 assert_eq!(ct, 2);
1822 }
1823
1824 #[test]
1825 fn encoding_resolve_and_length() {
1826 assert_eq!(resolve_encoding(None), None);
1828 assert_eq!(resolve_encoding(Some("")), None);
1829 assert_eq!(resolve_encoding(Some("utf-8")), Some(UTF_8));
1830 assert_eq!(resolve_encoding(Some("UTF8")), Some(UTF_8));
1831 assert_eq!(resolve_encoding(Some("gb18030")), Some(GB18030));
1832 assert_eq!(resolve_encoding(Some("GBK")), Some(GB18030));
1833 assert_eq!(resolve_encoding(Some("euc-kr")), Some(EUC_KR));
1834 assert_eq!(resolve_encoding(Some("latin1")), None); let s = "中文测试";
1838 assert_eq!(enc_str(UTF_8, s).len(), 12);
1839 assert_eq!(enc_str(GB18030, s).len(), 8);
1840 assert_eq!(lob_len(&Param::Str(s.into()), UTF_8), 12);
1841 assert_eq!(lob_len(&Param::Str(s.into()), GB18030), 8);
1842
1843 fn detect(opts: &[u8]) -> &'static Encoding {
1845 let code = i32::from_le_bytes(opts[8..12].try_into().unwrap());
1846 match code {
1847 1 => UTF_8,
1848 2 => EUC_KR,
1849 _ => GB18030,
1850 }
1851 }
1852 let mut opts = [0u8; 44];
1853 assert_eq!(detect(&opts), GB18030); opts[8..12].copy_from_slice(&1i32.to_le_bytes());
1855 assert_eq!(detect(&opts), UTF_8);
1856 opts[8..12].copy_from_slice(&2i32.to_le_bytes());
1857 assert_eq!(detect(&opts), EUC_KR);
1858 }
1859
1860 #[test]
1861 fn utf8_char_boundary_align() {
1862 let s = "一二三四五六七八九十"; let data = enc_str(UTF_8, s);
1865 let mut end = 7usize.min(data.len()); while end < data.len() && end > 0 && (0x80..=0xBF).contains(&data[end]) {
1867 end -= 1;
1868 }
1869 assert_eq!(end, 6);
1870 assert_eq!(&data[..end], "一二".as_bytes());
1871 }
1872
1873 #[test]
1874 fn server_params_parse() {
1875 let body = hex2b(
1877 "0700000004000000000000000100000000000000000000000000030000000000494e5413000000ffffff7f000000000100000000000000000000000000040000000000434c4f4200",
1878 );
1879 let params = parse_server_params(&body);
1880 assert_eq!(params.len(), 2);
1881 assert_eq!(params[0].col_type, 7);
1882 assert_eq!(params[0].prec, 4);
1883 assert_eq!(params[0].scale, 0);
1884 assert_eq!(params[1].col_type, 19); assert_eq!(params[1].prec, 0x7FFF_FFFF);
1886 }
1887
1888 fn hex2b(s: &str) -> Vec<u8> {
1889 (0..s.len())
1890 .step_by(2)
1891 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
1892 .collect()
1893 }
1894
1895 #[test]
1896 fn execute_opts_match_capture() {
1897 let c = DmClient::new("h", 1, "u", "p");
1899 let o = c.execute_opts(false);
1900 assert_eq!(
1901 &o[..19],
1902 &[
1903 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1904 0xff, 0x7f, 0x00, 0x00, 0x00, 0x01
1905 ]
1906 );
1907 let o = c.execute_opts(true);
1909 assert_eq!(
1910 &o[..19],
1911 &[
1912 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1913 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00
1914 ]
1915 );
1916 }
1917
1918 #[test]
1919 fn bind_opts_match_capture() {
1920 let mut c = DmClient::new("h", 1, "u", "p");
1923 c.auto_commit = true;
1924 let params = [Param::Int(1)];
1925 let mut opts = [0u8; 44];
1927 opts[0] = 1;
1928 opts[1..3].copy_from_slice(&1u16.to_le_bytes());
1929 opts[3] = 1;
1930 opts[4..12].copy_from_slice(&1i64.to_le_bytes());
1931 opts[20..28].copy_from_slice(&i64::MAX.to_le_bytes());
1932 opts[28] = 1;
1933 opts[32..36].copy_from_slice(&(-1i32).to_le_bytes());
1934 assert_eq!(&opts[0..12], &[0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1935 assert_eq!(&opts[20..36], &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
1936 let _ = ¶ms;
1937 }
1938
1939 #[test]
1940 fn date_str_parse() {
1941 let d = parse_date_str("2026-08-12").unwrap();
1942 assert_eq!(d, DmDate::new(2026, 8, 12));
1943 let t = parse_time_str("12:34:56.789").unwrap();
1944 assert_eq!(t, DmTime::new(12, 34, 56, 789000));
1945 let dt = to_datetime(&Param::Str("2030-06-15 08:09:10.111222".into())).unwrap();
1946 assert_eq!(dt, DmDateTime::new(DmDate::new(2030, 6, 15), DmTime::new(8, 9, 10, 111222)));
1947 }
1948}