Skip to main content

dm_pure/
client.rs

1//! 达梦 DM8 最小客户端(参照 dm-pure Python 驱动移植)。
2//!
3//! 连接流程: TCP → 握手(cmd=200) → 登录(cmd=1) → 会话查询(cmd=3) → 执行(cmd=5)
4
5use 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/// 存储过程 OUT 参数类型提示
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum OutType {
27    Bool,
28    Int,
29    Float,
30    Str,
31    Date,
32    DateTime,
33}
34
35/// 存储过程 OUT 参数标记:`execute("CALL proc(?, ?)", &[Param::Int(1), Param::out(Some(OutType::Int))])`
36#[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/// 绑定参数。
48#[derive(Debug, Clone, PartialEq)]
49pub enum Param {
50    Null,
51    Bool(bool),
52    /// 写(INSERT/UPDATE)用 INT(7)/prec4,查询参数用 BIGINT(8)/prec8
53    Int(i64),
54    Float(f64),
55    Str(String),
56    Bytes(Vec<u8>),
57    Date(DmDate),
58    Time(DmTime),
59    DateTime(DmDateTime),
60    /// 存储过程 OUT 参数(无输入数据)
61    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/// 服务器返回的参数元信息(cmd=5 响应 serverParams)。
77#[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/// 执行结果。
86#[derive(Debug, Clone, PartialEq)]
87pub enum ExecuteResult {
88    /// 查询:列描述符 + 行
89    Query {
90        columns: Vec<Column>,
91        rows: Vec<Vec<Value>>,
92    },
93    /// DML:影响行数
94    Affected(u64),
95    /// 存储过程 CALL:影响行数 + OUT 参数值
96    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/// 客户端配置。
124#[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    /// 连接/读写超时
133    pub timeout: Duration,
134    /// 断线自动重连
135    pub auto_reconnect: bool,
136    /// 每帧发送后的间隔(Rust 端单帧 write_all + TCP_NODELAY,默认 0 即可;
137    /// 若遇帧合并问题可设 send_delay_ms 恢复间隔)
138    pub send_delay: Duration,
139    /// 服务器字符集。None=连接握手时自动检测(响应偏移 28:1=UTF8, 2=EUCKR,
140    /// 其他=GB18030);也可手动指定 "GB18030"/"UTF-8"/"EUC-KR" 覆盖检测。
141    /// 默认自动检测——服务器为 UTF-8 而按 GB18030 编解码是中文乱码的根因。
142    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            // Rust 端 send_frame 单次 write_all 写完一整个帧 + TCP_NODELAY 禁用 Nagle,
157            // 独立 TCP 段有保证,无需 sleep(默认 0;Python 端保留 2ms 因为 sendall 可能被合并)
158            send_delay: Duration::ZERO,
159            encoding: None,
160        }
161    }
162}
163
164/// 将用户指定的编码名解析为 encoding_rs 编码。未指定或无法识别返回 None(自动检测)。
165fn 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/// 惰性查询状态(execute_lazy 返回,fetch_more / close_lazy 使用)。
186#[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
195/// 达梦客户端:连接 / 查询 / 参数绑定 / LOB / 事务 / 存储过程 / 惰性查询。
196pub struct DmClient {
197    cfg: ClientConfig,
198    reader: Option<FrameReader>,
199    session_key: Option<Vec<u8>>,
200    cipher: Option<SymmCipher>,
201    /// execute 时 +1 从 0 开始连续递增(槽位 0-63 循环)
202    stmt_id: i32,
203    /// 服务器编码(登录后确定,默认 GB18030)
204    svr_encoding: &'static Encoding,
205    auto_commit: bool,
206    /// 是否处于事务中(begin 后 commit/rollback 前)——断线重连保护
207    in_transaction: bool,
208    /// 大 LOB 分块大小
209    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    /// 从 DSN 连接串创建客户端(不连接):`dm://user:password@host:port/?encoding=utf8&timeout=15`。
224    /// 支持参数:encoding(字符集)、timeout(秒)、auto_reconnect(true/false)、
225    /// send_delay_ms(帧间隔毫秒)、app_name、os_name。
226    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        // user:pass@host:port
234        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    /// 从 DSN 连接串创建并连接:`dm://SYSDBA:password@127.0.0.1:5236/?encoding=auto`。
273    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            // 手动指定优先;否则先用 GB18030 占位,握手后按服务器响应自动切换
288            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    /// 当前使用的服务器字符集名(握手自动检测或手动指定,如 "GB18030"/"UTF-8"/"EUC-KR")。
312    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    // ---------- 底层收发 ----------
321
322    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        // 服务器错误 body 结构:[二进制头][int32 消息长度][消息文本],
351        // 去掉前导控制字符/NUL,只保留可读消息(如 "用户名或密码错误")。
352        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    // ---------- 连接 ----------
366
367    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; // 新会话重置 stmt 槽位
377        self.auto_commit = true;
378        self.in_transaction = false; // 新会话无事务
379        Ok(())
380    }
381
382    fn ensure_connection(&mut self) -> Result<()> {
383        if self.reader.is_none() {
384            if self.in_transaction {
385                // 事务中途断线:不静默重连(新会话会丢失未提交事务),改为明确报错
386                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        // 参数区(照抓包实测值)
400        let mut opts = [0u8; 44];
401        opts[..17].copy_from_slice(&[
402            0x00, 0x00, 0x00, 0x00, // 20: int32 0
403            0x00, 0x00, 0x00, 0x00, // 24: int32 compress=0
404            0x01, 0x02, // 28: loginEncrypt 低=1, 高=2
405            0x00, 0x00, // 30: isBdtaRS=0, compressID=0
406            0x00, 0x00, // 32: loginCert=0, 33: 0
407            0x01, 0x08, // 34: 1, 35: uint16 MsgVersion=8
408            0x00, // 36: 0
409        ]);
410        let mut body = Vec::with_capacity(81);
411        body.extend_from_slice(&8i32.to_le_bytes()); // 版本长度
412        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        // 服务器编码在握手响应参数区偏移 28(int32):1=UTF8, 2=EUCKR, 其他=GB18030
421        // (对照 Go 驱动 zq.go Dm_build_1282 = 28)。未手动指定时自动适配:
422        // 服务器若为 UTF-8 而客户端按 GB18030 编解码,中文会乱码。
423        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        // 解析握手响应:找服务器 DH 公钥([int32 64][64字节公钥])
433        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        // 计算会话密钥 + 登录加密通道(DES_CFB)
454        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        // 参数区(严格照 Go 抓包:帧40=00, 帧41=01)
462        let mut opts = [0u8; 44];
463        opts[..23].copy_from_slice(&[
464            0x05, 0x00, 0x00, 0x00, // 20: clientType=5
465            0xff, 0xff, 0xff, 0xff, // 24: isoLevel=-1
466            0x00, 0x00, 0x00, 0x00, // 28: locale=0
467            0x00, 0xe0, // 32: int16 timezone
468            0x01, // 34: 1
469            0x00, 0x00, 0x00, 0x00, // 35: sessionTimeout
470            0x00, // 39: 0
471            0x00, // 40: 0
472            0x01, // 41: 1
473            0x00, // 42: osAuthType
474        ]);
475        let cipher = self.cipher.as_ref().ok_or_else(|| DmError::protocol("未握手"))?;
476
477        // 用户名/密码:UTF-8 编码 + DES_CFB 加密(流式,长度不变)
478        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        // 应用信息(照 Go 结构:appName/hostName 空,osName 填 linux)
487        body.extend_from_slice(&0i32.to_le_bytes()); // appName 空
488        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()); // hostName 空
492        body.push(0); // rwStandby
493        body.extend_from_slice(&0u16.to_le_bytes()); // serverOption: [uint16 len] 空
494
495        self.send(CMD_LOGIN, &opts, &body, 0)?;
496        self.recv(163)?;
497        Ok(())
498    }
499
500    // ---------- 会话查询(每条 SQL 前) ----------
501
502    /// 会话查询(cmd=3)。返回服务器回显的 stmt 号——实测(DM8 x64 V8):
503    /// 服务器在 cmd=187(24) 响应中回显“下一个可用 stmt 号”,cmd=5 必须使用该号,
504    /// 否则报 -7003 无效语句句柄(本机自增计数与服务器不一致时触发)。
505    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    // ---------- 执行 ----------
515
516    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; // autoCommit
520        // 参数化 SQL 一律用 DML 参数区(opts21=00);非参数化用 opts21=01 直接执行(抓包实测)
521        opts[1] = if has_params { 0 } else { 1 };
522        opts[3] = 1;
523        opts[7..15].copy_from_slice(&i64::MAX.to_le_bytes()); // maxRows
524        if !has_params {
525            opts[18] = 1; // isBdtaRS 标志(仅非参数化)
526        }
527        opts
528    }
529
530    /// 执行 SQL。`params` 为参数化查询的绑定参数。
531    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            // 先读 cmd=5 响应(prepare:DML 返回 serverParams;SELECT 返回列描述符)
552            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            // 大 LOB 参数(≥8188B)先通过 cmd=90/14 写入,cmd=13 传长度 0
560            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            // 参数化 DML:cmd=13 后必须先读绑定响应,再发 cmd=4(新版本 DM8 服务器实测:
566            // 背靠背发送 cmd=13+cmd=4 会报 "comm msg recv empty msg" 并断开连接)
567            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        // 读取响应序列:结果帧为 cmd=187(结果集或影响行数);cmd=0 是中间状态帧,继续读
578        let mut frames: Vec<Frame> = prep_frames;
579        for _ in 0..4 {
580            // 若 cmd=13 响应已含结果帧(cmd=187),不再阻塞读取
581            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                // 普通查询结果集帧
600                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                    // 大结果集:帧24-25=65535(0xFFFF)表示还有更多行,发 cmd=7 拉剩余(循环直到取完)
606                    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                        // cmd=44(取结果完成)→ cmd=0(34, ret=111);先读掉,否则 LOB 解码的 cmd=29 读到它
611                        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                // 参数化 SELECT(Execute2):cmd=0 含参数回显+列描述符(列描述符在 len(params)*32,
619                // DDL 后首条可能多 8B 类型名,用 parse_cols_robust 自适应定位)
620                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                    // 行数据在 cmd=187(cmd=13 响应)
624                    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                                // 大结果集:列描述符 + fetchSize 行(行长循环)
631                                let (_, pos2) = parse_columns(&f2.body, 0, ncols2, self.svr_encoding)?;
632                                rows_raw = parse_rows_param(&f2.body, pos2, ncols2)?;
633                            } else {
634                                // 小结果集:纯行数据
635                                rows_raw = parse_rows_param(&f2.body, 0, ncols)?;
636                            }
637                            // 分批 fetch:帧24-25=65535(0xFFFF)表示还有更多行,发 cmd=7 拉剩余
638                            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                            // cmd=44(取结果完成)→ cmd=0(34, ret=111);先读掉,否则 LOB 解码的 cmd=29 读到它
644                            let _ = self.send(CMD_FETCH, &[], &[], stmt).and_then(|_| self.read_frame());
645                            // LOB 解码(cmd=29/32 用 stmt,此时未释放)
646                            let rows = self.decode_rows(&cols, &rows_raw, stmt)?;
647                            // cmd=4(释放)→ cmd=0(24)
648                            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                // DML 结果:影响行数在帧头参数区偏移 24(int64,Go zq.go Dm_build_354)
656                let affected = le_i64(&f.opts, 4) as u64;
657                // CALL 存储过程:cmd=187 小帧可能含 OUT 参数值(uint16 长度+数据)
658                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(); // cmd=4 确认
662                    }
663                    result = Some(ExecuteResult::Call { affected, out });
664                } else {
665                    // 参数化 DML:cmd=4 的确认响应(cmd=0 len=24)在结果帧后,必须读掉防残留
666                    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        // 释放语句(每条 SQL 后发 cmd=4)——仅非参数化时在此补发
676        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    /// 惰性查询:只拉第一帧(fetchSize 行),返回 (cols, state)。
683    /// 调用方用 `fetch_more` 按需拉取;用完必须 `close_lazy`。
684    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        // 读 cmd=13 响应(第一帧:cmd=187)
704        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    /// 惰性拉取下一批(cmd=7),循环直到取完全部行。返回追加的行(raw)。之后 `state.more` 为 false。
724    ///
725    /// 请求参数区:帧 20-27=startPos(int64),28-35=INT64_MAX(maxRows),36-39=id,40-43=bufPrefetch。
726    /// 响应参数区:帧 20-27=总行数 int64(Go zq.go `Dm_build_1068=20` / updateCount),
727    /// 帧 28-31=本批行数 int32(`Dm_build_1069=28`)。
728    /// 循环保护:空批即断 + 最大迭代上限(防服务器不返回总行数时误判死循环)。
729    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; // 服务器回显总行数(cmd=7 响应 opts[0..8]);-1=未知
734        for _ in 0..MAX_FETCH_ITERS {
735            // 已取完(start >= 总行数):不再发可能超界的 cmd=7(bug:恰在分页边界时误报)
736            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            // 帧 36-39=id int32, 40-43=bufPrefetch int32(0)
743            self.send(7, &opts, &[], stmt)?;
744            let f = self.read_frame()?;
745            if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
746                // 恰好在分页边界(start==total,上批已取完)时,服务器对超界 cmd=7 返回
747                // "无更多数据"类错误码;此时首帧已取走全部行,应视为正常结束而非报错。
748                break;
749            }
750            // 响应参数区:opts[0..8]=总行数 int64(updateCount),opts[8..12]=本批行数 int32
751            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; // 空批 → 数据已取完
759            }
760            start += n as i64;
761            all.extend(rows);
762        }
763        Ok(all)
764    }
765
766    /// 释放惰性查询的 stmt(cmd=44 + cmd=4)。
767    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    /// 批量执行(协议级 batch,一组 cmd=5+13+4 插多行)。返回总影响行数。
779    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        // cmd=5 响应(prepare:serverParams)必须读掉,再发 cmd=13
790        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, &params_list[0], false, Some(params_list), server_params.as_deref())?;
800        // cmd=13 响应必须读掉,再发 cmd=4(背靠背会导致服务器断连)
801        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        // 结果帧:cmd=13 响应即 cmd=187(影响行数在 opts[4..6]);cmd=4 确认是 cmd=0(24)
807        let mut affected = 0u64;
808        if f13.cmd == 187 {
809            affected = le_u16(&f13.opts, 4) as u64;
810            let _ = self.read_frame(); // cmd=4 确认
811        } 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(); // cmd=4 确认
820                    break;
821                }
822            }
823        }
824        Ok(affected)
825    }
826
827    // ---------- 行/值解码 ----------
828
829    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            // 行内 LOB:头部 43 字节,数据 @43,长度 @9
865            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            // 非行内:43 字节定位符 → cmd=32 分段读取
869            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        // CLOB:offset/req 为字符数(cmd=29 得字符长,单次 ≤16000);BLOB:字节(单次 ≤32000)
898        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            // cmd=32 参数区:lobFlag+tabId+colId+blobId+groupId+fileId+pageNo+curFileId+curPageNo+totalOffset+offset+length+rowId+exGroupId+exFileId+exPageNo
914            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            // BLOB:length 是字节数
960            Ok(all[..(length as usize).min(all.len())].to_vec())
961        }
962    }
963
964    #[allow(clippy::too_many_arguments)] // 与 Go/Python 驱动 LOB 定位符字段一一对应
965    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        // cmd=29:获取 CLOB 字符数(len=39)
981        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    // ---------- 参数绑定 ----------
1040
1041    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        // 参数区
1058        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()); // maxRows
1064        opts[28] = 1;
1065        opts[32..36].copy_from_slice(&(-1i32).to_le_bytes()); // queryTimeout = -1
1066
1067        // 参数描述(以第一组为准)
1068        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                // OUT 参数:ioType=1,colType 用 serverParams(否则按类型提示)
1073                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                // 大 LOB 参数:CLOB(19)/BLOB(12) + prec=0x7fffffff(已通过 cmd=90/14 写入)
1087            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        // 参数数据
1110        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; // OUT 参数无数据
1115                }
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()); // 大 LOB 已通过 cmd=90/14 写入
1126                    } 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        // 参数描述:小参数用 serverParams 类型;大值用 BLOB(12)/CLOB(19) + 0x7fffffff
1147        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        // cmd=90:LOB 参数声明(opts 帧20-21 = 参数个数)
1168        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        // cmd=14:分块写入每个大 LOB 参数(顺序与参数一致)
1176        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; // 参数索引(0 基,Go: dm_build_665(..., icol, ...))
1187            let mut off = 0;
1188            while off < data.len() {
1189                let mut end = (off + self.lob_chunk_size).min(data.len());
1190                // 多字节编码字符边界对齐,避免分块切半导致乱码:
1191                // GB18030/EUC-KR:块末是首字节(0x81-0xFE)且下一字节是尾字节(0x40-0xFE)时回退;
1192                // UTF-8:下一字节是续字节(0x80-0xBF)时回退到字符起点
1193                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    // ---------- 事务 ----------
1223
1224    /// 开始事务:设置隔离级别(cmd=52)+ 关闭自动提交(Go 实测顺序)
1225    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    /// 提交事务(cmd=8)
1235    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    /// 回滚事务(cmd=9)
1245    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    /// 设置事务隔离级别(cmd=52):1=读已提交 2=可重复读 3=串行化
1255    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    /// 用服务器编码编码字符串(SQL 文本 / 字符串参数 / CLOB 写入)。
1267    fn encode_str(&self, s: &str) -> Vec<u8> {
1268        enc_str(self.svr_encoding, s)
1269    }
1270
1271    /// 用服务器编码解码(错误消息等),损坏字节替换为 U+FFFD。
1272    fn decode_lossy(&self, b: &[u8]) -> String {
1273        let (s, _, _) = self.svr_encoding.decode(b);
1274        s.into_owned()
1275    }
1276}
1277
1278// ---------- 工具函数 ----------
1279
1280pub(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
1289/// 按指定服务器编码编码字符串(SQL 文本 / 字符串参数 / CLOB 写入)。
1290pub(crate) fn enc_str(enc: &'static Encoding, s: &str) -> Vec<u8> {
1291    enc.encode(s).0.into_owned()
1292}
1293
1294/// 科学计数法/带点字符串 → 定点十进制字符串(enc_decimal 用)
1295fn 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
1317/// 达梦私有大数二进制编码(与 Python _enc_decimal / Go encodeDecimal 一致)。
1318/// 输入十进制字符串(可含小数点与 e 科学计数),输出如 1.50 → c1 02 33,0 → 80。
1319pub(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    // 科学计数 → 定点
1330    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    // 构造 (weight, digits)
1338    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    // 去尾随 0
1351    while digits.ends_with('0') && digits.len() > 1 {
1352        digits.pop();
1353        weight += 1;
1354    }
1355    // 数值为零(如 "0.00"、"0.000")→ 0x80
1356    if digits.chars().all(|c| c == '0') {
1357        return vec![0x80];
1358    }
1359    // 对齐到 2 位一组
1360    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    // encodeDecimal
1368    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(); // 溢出(DECIMAL(38) 正常范围不会触发)
1372    }
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
1401/// 参数值字节长度(str 按服务器编码;bytes 原长)
1402pub(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
1410/// 参数类型猜测 → (colType, prec, scale, 编码器),对照 Go 驱动实测:
1411/// int→INT(7)/prec4, str→VARCHAR(2)/prec=len, float→DOUBLE(11)/prec8,
1412/// date→DATE(14)/prec3, None→NULL
1413/// 带时区(timezone_minutes=Some)自动升为 TZ 类型:TIME_TZ(22)/DATETIME_TZ(23)
1414fn 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            // 查询参数用 BIGINT(8)/prec8(Go 实测),写入用 INT(7)/prec4
1419            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            // 查询参数 prec=8188(0x1FFC);写入参数 prec=列长度(用 50 或实际长度)
1445            let prec = if is_query { 8188 } else { 50.max(len as i32) };
1446            (2, prec, 0, ParamEncoder::Str)
1447        }
1448        Param::Null => {
1449            // NULL 参数:VARCHAR(2)/prec=8188
1450            (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
1478/// 解析 cmd=5 响应(DML prepare)的 serverParams。
1479pub 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; // itemFlag
1492        pos += 4; // 跳过
1493        if pos + 2 > n {
1494            break;
1495        }
1496        let io_type = body[pos] as i32;
1497        pos += 2; // ioType 是 int16(Go: int8(Dm_build_204()),消耗 2 字节)
1498        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        // 名称描述完后通常还有 baseName 或尾部;用"合理 colType"判断终止
1513        if !(0..=40).contains(&col_type) {
1514            break;
1515        }
1516    }
1517    params
1518}
1519
1520/// 按服务器参数类型返回编码器(serverParams 优先于类型猜测)
1521#[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, // CHAR/VARCHAR2/VARCHAR/CLOB
1546            9 => ParamEncoder::Decimal,           // DECIMAL:私有大数二进制
1547            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, // TIME_TZ
1557            16 => ParamEncoder::DateTime,
1558            23 => ParamEncoder::DateTimeTz, // DATETIME_TZ
1559            26 => ParamEncoder::DateTime2,  // DATETIME2
1560            27 => ParamEncoder::DateTime2Tz, // DATETIME2_TZ
1561            12 | 17 | 18 => ParamEncoder::Bytes, // BLOB/BINARY/VARBINARY
1562            _ => 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            // 兼容 "YYYY-MM-DD HH:MM:SS[.ffffff]" 与纯日期
1651            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
1678/// 解析 "YYYY-MM-DD"
1679fn 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
1690/// 解析 "HH:MM:SS[.ffffff]"
1691fn 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        // col_type=9 → ParamEncoder::Decimal;float/str/int 参数都走它(私有大数二进制)
1744        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); // GB18030 8 字节 < 50
1774
1775        // UTF-8 下 "测试" 6 字节,仍 < 50
1776        let (ct, prec, _, _) = param_type(&Param::Str("测试".into()), false, UTF_8);
1777        assert_eq!(ct, 2);
1778        assert_eq!(prec, 50);
1779
1780        // UTF-8 下超长字符串按字节长计算 prec(区别于 GB18030 的字节长)
1781        let s = "中".repeat(30); // UTF-8 90 字节
1782        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); // GB18030 60 字节
1786
1787        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        // 带时区:TIME_TZ(22)/DATETIME_TZ(23)
1795        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        // 无时区保持普通类型
1808        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        // 编码名解析(不区分大小写)
1827        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); // 未识别 → 自动检测
1835
1836        // 编码字节长度:UTF-8 中文 3 字节/字,GB18030 2 字节/字
1837        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        // 握手响应编码码值映射(Go 驱动逻辑:1=UTF8, 2=EUCKR, 其他=GB18030)
1844        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); // 0 → GB18030
1854        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        // UTF-8 分块对齐:块末若切在续字节则回退到字符起点
1863        let s = "一二三四五六七八九十"; // 30 字节 UTF-8
1864        let data = enc_str(UTF_8, s);
1865        let mut end = 7usize.min(data.len()); // 切在 "三" 中间(字节 6-8)
1866        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        // 抓包实测:INSERT INTO lob_test3 (id, data) VALUES (?, ?) 的 prepare 响应 (cmd=0 len=72)
1876        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); // CLOB
1885        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        // 非参数化 SELECT 抓包实测:01 01 00 01 00 00 00 ff ff ff ff ff ff ff 7f 00 00 00 01
1898        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        // 参数化 SQL 抓包实测:01 00 00 01 00 00 00 ff ff ff ff ff ff ff 7f 00 00 00 00
1908        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        // 抓包实测 cmd=13 参数区(1 参数 batch=1):
1921        // 01 01 00 01 01 00 00 00 ... ff ff ff ff ff ff ff 7f 01 00 00 00 ff ff ff ff
1922        let mut c = DmClient::new("h", 1, "u", "p");
1923        c.auto_commit = true;
1924        let params = [Param::Int(1)];
1925        // 直接构造 opts 校验(通过 bind_params 无法断言,这里独立复现)
1926        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 _ = &params;
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}