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        for _ in 0..MAX_FETCH_ITERS {
734            let mut opts = [0u8; 44];
735            opts[..8].copy_from_slice(&start.to_le_bytes());
736            opts[8..16].copy_from_slice(&i64::MAX.to_le_bytes());
737            // 帧 36-39=id int32, 40-43=bufPrefetch int32(0)
738            self.send(7, &opts, &[], stmt)?;
739            let f = self.read_frame()?;
740            if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
741                return Err(self.server_error(&f));
742            }
743            // 响应参数区:opts[0..8]=总行数 int64(updateCount),opts[8..12]=本批行数 int32
744            let total = le_i64(&f.opts, 0);
745            let rows = parse_rows_param(&f.body, 0, ncols)?;
746            let n = rows.len();
747            if n == 0 {
748                break; // 空批 → 数据已取完
749            }
750            start += n as i64;
751            all.extend(rows);
752            // 总行数已知(≠INT64_MAX 且 >0)且已取完 → 结束;否则继续拉下一批
753            if total != i64::MAX && total > 0 && start >= total {
754                break;
755            }
756        }
757        Ok(all)
758    }
759
760    /// 释放惰性查询的 stmt(cmd=44 + cmd=4)。
761    pub fn close_lazy(&mut self, state: &mut LazyState) -> Result<()> {
762        if state.closed {
763            return Ok(());
764        }
765        let stmt = state.stmt;
766        let _ = self.send(CMD_FETCH, &[], &[], stmt).and_then(|_| self.read_frame());
767        let _ = self.send(CMD_EXEC_COMPLETE, &[0u8; 44], &[], stmt).and_then(|_| self.read_frame());
768        state.closed = true;
769        Ok(())
770    }
771
772    /// 批量执行(协议级 batch,一组 cmd=5+13+4 插多行)。返回总影响行数。
773    pub fn executemany(&mut self, sql: &str, params_list: &[Vec<Param>]) -> Result<u64> {
774        self.ensure_connection()?;
775        let stmt = self.session_query()?;
776        if is_query_sql(sql) {
777            return Err(DmError::arg("executemany 仅支持 DML"));
778        }
779        let opts = self.execute_opts(true);
780        let mut sql_bytes = self.encode_str(sql);
781        sql_bytes.push(0);
782        self.send(CMD_EXECUTE, &opts, &sql_bytes, stmt)?;
783        // cmd=5 响应(prepare:serverParams)必须读掉,再发 cmd=13
784        let prep = self.read_frame()?;
785        if prep.retcode != 0 && prep.retcode != 111 {
786            return Err(self.server_error(&prep));
787        }
788        let server_params = if prep.cmd == 0 {
789            Some(parse_server_params(&prep.body))
790        } else {
791            None
792        };
793        self.bind_params(stmt, &params_list[0], false, Some(params_list), server_params.as_deref())?;
794        // cmd=13 响应必须读掉,再发 cmd=4(背靠背会导致服务器断连)
795        let f13 = self.read_frame()?;
796        if f13.retcode != 0 && f13.retcode != 111 && f13.retcode != 100 {
797            return Err(self.server_error(&f13));
798        }
799        self.send(CMD_EXEC_COMPLETE, &[0u8; 44], &[], stmt)?;
800        // 结果帧:cmd=13 响应即 cmd=187(影响行数在 opts[4..6]);cmd=4 确认是 cmd=0(24)
801        let mut affected = 0u64;
802        if f13.cmd == 187 {
803            affected = le_u16(&f13.opts, 4) as u64;
804            let _ = self.read_frame(); // cmd=4 确认
805        } else {
806            for _ in 0..4 {
807                let f = self.read_frame()?;
808                if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
809                    return Err(self.server_error(&f));
810                }
811                if f.cmd == 187 {
812                    affected = le_u16(&f.opts, 4) as u64;
813                    let _ = self.read_frame(); // cmd=4 确认
814                    break;
815                }
816            }
817        }
818        Ok(affected)
819    }
820
821    // ---------- 行/值解码 ----------
822
823    pub(crate) fn decode_rows(&mut self, cols: &[Column], rows: &[Row], stmt: i32) -> Result<Vec<Vec<Value>>> {
824        let mut out = Vec::with_capacity(rows.len());
825        for r in rows {
826            let mut v = Vec::with_capacity(r.len());
827            for (i, cell) in r.iter().enumerate() {
828                let val = match cell {
829                    None => Value::Null,
830                    Some(raw) => {
831                        let col = if i < cols.len() { &cols[i] } else { continue; };
832                        self.decode_value(raw, col, Some(stmt))?
833                    }
834                };
835                v.push(val);
836            }
837            out.push(v);
838        }
839        Ok(out)
840    }
841
842    fn decode_value(&mut self, raw: &[u8], col: &Column, stmt: Option<i32>) -> Result<Value> {
843        if col.col_type == DM_CLOB || col.col_type == DM_BLOB {
844            return self.read_lob(raw, col, stmt);
845        }
846        decode_scalar(raw, col, self.svr_encoding)
847    }
848
849    fn read_lob(&mut self, raw: &[u8], col: &Column, stmt: Option<i32>) -> Result<Value> {
850        if raw.is_empty() {
851            return Ok(if col.col_type == DM_CLOB {
852                Value::Str(String::new())
853            } else {
854                Value::Bytes(Vec::new())
855            });
856        }
857        let data: Vec<u8> = if raw[0] == 0x01 && raw.len() >= 43 {
858            // 行内 LOB:头部 43 字节,数据 @43,长度 @9
859            let length = u32::from_le_bytes(raw[9..13].try_into().unwrap()) as usize;
860            raw[43..(43 + length).min(raw.len())].to_vec()
861        } else {
862            // 非行内:43 字节定位符 → cmd=32 分段读取
863            self.read_offrow_lob(raw, col, stmt)?
864        };
865        if col.col_type == DM_CLOB {
866            let (s, _, _) = self.svr_encoding.decode(&data);
867            Ok(Value::Str(s.into_owned()))
868        } else {
869            Ok(Value::Bytes(data))
870        }
871    }
872
873    fn read_offrow_lob(&mut self, desc: &[u8], col: &Column, stmt: Option<i32>) -> Result<Vec<u8>> {
874        if desc.len() < 43 {
875            return Ok(Vec::new());
876        }
877        let blob_id = i64::from_le_bytes(desc[1..9].try_into().unwrap());
878        let length = u32::from_le_bytes(desc[9..13].try_into().unwrap()) as i64;
879        let group_id = i16::from_le_bytes(desc[13..15].try_into().unwrap());
880        let file_id = i16::from_le_bytes(desc[15..17].try_into().unwrap());
881        let page_no = i32::from_le_bytes(desc[17..21].try_into().unwrap());
882        let tab_id = i32::from_le_bytes(desc[21..25].try_into().unwrap());
883        let col_id = i16::from_le_bytes(desc[25..27].try_into().unwrap());
884        let row_id = i64::from_le_bytes(desc[27..35].try_into().unwrap());
885        let ex_group = i16::from_le_bytes(desc[35..37].try_into().unwrap());
886        let ex_file = i16::from_le_bytes(desc[37..39].try_into().unwrap());
887        let ex_page = i32::from_le_bytes(desc[39..43].try_into().unwrap());
888
889        let is_clob = col.col_type == DM_CLOB;
890        let lob_flag: u8 = if is_clob { 1 } else { 0 };
891        // CLOB:offset/req 为字符数(cmd=29 得字符长,单次 ≤16000);BLOB:字节(单次 ≤32000)
892        let mut length = length;
893        let req_unit: i64 = if is_clob { 16000 } else { 32000 };
894        if is_clob {
895            length = self.lob_char_len(
896                lob_flag, blob_id, group_id, file_id, page_no, tab_id, col_id, row_id,
897                ex_group, ex_file, ex_page, stmt,
898            )?;
899        }
900        let mut all: Vec<u8> = Vec::new();
901        let mut offset: i64 = 0;
902        let mut cur_file = file_id;
903        let mut cur_page = page_no;
904        let mut total_offset: i32 = 0;
905        while offset < length {
906            let req = req_unit.min(length - offset);
907            // cmd=32 参数区:lobFlag+tabId+colId+blobId+groupId+fileId+pageNo+curFileId+curPageNo+totalOffset+offset+length+rowId+exGroupId+exFileId+exPageNo
908            let mut body = Vec::with_capacity(59);
909            body.push(lob_flag);
910            body.extend_from_slice(&tab_id.to_le_bytes());
911            body.extend_from_slice(&col_id.to_le_bytes());
912            body.extend_from_slice(&blob_id.to_le_bytes());
913            body.extend_from_slice(&group_id.to_le_bytes());
914            body.extend_from_slice(&file_id.to_le_bytes());
915            body.extend_from_slice(&page_no.to_le_bytes());
916            body.extend_from_slice(&cur_file.to_le_bytes());
917            body.extend_from_slice(&cur_page.to_le_bytes());
918            body.extend_from_slice(&total_offset.to_le_bytes());
919            body.extend_from_slice(&offset.to_le_bytes());
920            body.extend_from_slice(&req.to_le_bytes());
921            body.extend_from_slice(&row_id.to_le_bytes());
922            body.extend_from_slice(&ex_group.to_le_bytes());
923            body.extend_from_slice(&ex_file.to_le_bytes());
924            body.extend_from_slice(&ex_page.to_le_bytes());
925
926            self.send(32, &[], &body, stmt.unwrap_or(0))?;
927            let f = self.read_frame()?;
928            if f.retcode != 0 && f.retcode != 111 {
929                return Err(self.server_error(&f));
930            }
931            if f.body.len() < 15 {
932                break;
933            }
934            let read_over = f.body[0];
935            let dlen = i32::from_le_bytes(f.body[1..5].try_into().unwrap());
936            if dlen <= 0 {
937                break;
938            }
939            let dlen = dlen as usize;
940            let end = (15 + dlen).min(f.body.len());
941            all.extend_from_slice(&f.body[15..end]);
942            cur_file = i16::from_le_bytes(f.body[5..7].try_into().unwrap());
943            cur_page = i32::from_le_bytes(f.body[7..11].try_into().unwrap());
944            total_offset = i32::from_le_bytes(f.body[11..15].try_into().unwrap());
945            offset += if is_clob { req } else { dlen as i64 };
946            if read_over != 0 {
947                break;
948            }
949        }
950        if is_clob {
951            Ok(all)
952        } else {
953            // BLOB:length 是字节数
954            Ok(all[..(length as usize).min(all.len())].to_vec())
955        }
956    }
957
958    #[allow(clippy::too_many_arguments)] // 与 Go/Python 驱动 LOB 定位符字段一一对应
959    fn lob_char_len(
960        &mut self,
961        lob_flag: u8,
962        blob_id: i64,
963        group_id: i16,
964        file_id: i16,
965        page_no: i32,
966        tab_id: i32,
967        col_id: i16,
968        row_id: i64,
969        ex_group: i16,
970        ex_file: i16,
971        ex_page: i32,
972        stmt: Option<i32>,
973    ) -> Result<i64> {
974        // cmd=29:获取 CLOB 字符数(len=39)
975        let mut body = Vec::with_capacity(39);
976        body.push(lob_flag);
977        body.extend_from_slice(&blob_id.to_le_bytes());
978        body.extend_from_slice(&group_id.to_le_bytes());
979        body.extend_from_slice(&file_id.to_le_bytes());
980        body.extend_from_slice(&page_no.to_le_bytes());
981        body.extend_from_slice(&tab_id.to_le_bytes());
982        body.extend_from_slice(&col_id.to_le_bytes());
983        body.extend_from_slice(&row_id.to_le_bytes());
984        body.extend_from_slice(&ex_group.to_le_bytes());
985        body.extend_from_slice(&ex_file.to_le_bytes());
986        body.extend_from_slice(&ex_page.to_le_bytes());
987        self.send(29, &[], &body, stmt.unwrap_or(0))?;
988        let f = self.read_frame()?;
989        if f.retcode != 0 && f.retcode != 111 {
990            return Err(self.server_error(&f));
991        }
992        if f.body.len() >= 8 {
993            return Ok(i64::from_le_bytes(f.body[..8].try_into().unwrap()));
994        }
995        if f.body.len() >= 4 {
996            return Ok(i32::from_le_bytes(f.body[..4].try_into().unwrap()) as i64);
997        }
998        Ok(0)
999    }
1000
1001    fn parse_out_values(
1002        &mut self,
1003        body: &[u8],
1004        out_indices: &[usize],
1005        server_params: Option<&[ServerParam]>,
1006    ) -> Vec<Value> {
1007        let mut values = Vec::new();
1008        let mut pos = 0usize;
1009        for &idx in out_indices {
1010            if pos + 2 > body.len() {
1011                values.push(Value::Null);
1012                break;
1013            }
1014            let ln = u16::from_le_bytes(body[pos..pos + 2].try_into().unwrap());
1015            pos += 2;
1016            if ln == NULL_MARK {
1017                values.push(Value::Null);
1018                continue;
1019            }
1020            if pos + ln as usize > body.len() {
1021                values.push(Value::Null);
1022                break;
1023            }
1024            let raw = &body[pos..pos + ln as usize];
1025            pos += ln as usize;
1026            let sp = server_params.and_then(|s| s.get(idx));
1027            let ct = sp.map(|x| x.col_type).unwrap_or(2);
1028            values.push(decode_out_value(raw, ct, self.svr_encoding));
1029        }
1030        values
1031    }
1032
1033    // ---------- 参数绑定 ----------
1034
1035    fn bind_params(
1036        &mut self,
1037        stmt: i32,
1038        params: &[Param],
1039        is_query: bool,
1040        batch_list: Option<&[Vec<Param>]>,
1041        server_params: Option<&[ServerParam]>,
1042    ) -> Result<()> {
1043        let groups: Vec<&[Param]> = match batch_list {
1044            Some(bl) => bl.iter().map(|g| g.as_slice()).collect(),
1045            None => vec![params],
1046        };
1047        let first = groups[0];
1048        let n_params = first.len();
1049        let n_batch = groups.len();
1050
1051        // 参数区
1052        let mut opts = [0u8; 44];
1053        opts[0] = if self.auto_commit { 1 } else { 0 };
1054        opts[1..3].copy_from_slice(&(n_params as u16).to_le_bytes());
1055        opts[3] = 1;
1056        opts[4..12].copy_from_slice(&(n_batch as i64).to_le_bytes());
1057        opts[20..28].copy_from_slice(&i64::MAX.to_le_bytes()); // maxRows
1058        opts[28] = 1;
1059        opts[32..36].copy_from_slice(&(-1i32).to_le_bytes()); // queryTimeout = -1
1060
1061        // 参数描述(以第一组为准)
1062        let mut desc = Vec::with_capacity(n_params * 13);
1063        let mut encoders: Vec<Option<ParamEncoder>> = Vec::with_capacity(n_params);
1064        for (i, p) in first.iter().enumerate() {
1065            if let Param::Out(hint) = p {
1066                // OUT 参数:ioType=1,colType 用 serverParams(否则按类型提示)
1067                let sp = server_params.and_then(|s| s.get(i));
1068                let ct = sp.map(|x| x.col_type).unwrap_or_else(|| out_type_hint(*hint));
1069                let prec = sp.map(|x| x.prec).unwrap_or_else(|| out_type_prec(*hint));
1070                let scale = sp.map(|x| x.scale).unwrap_or(0);
1071                desc.extend_from_slice(&1i8.to_le_bytes());
1072                desc.extend_from_slice(&ct.to_le_bytes());
1073                desc.extend_from_slice(&prec.to_le_bytes());
1074                desc.extend_from_slice(&scale.to_le_bytes());
1075                encoders.push(None);
1076                continue;
1077            }
1078            let is_lob = lob_len(p, self.svr_encoding) >= 8188;
1079            if is_lob {
1080                // 大 LOB 参数:CLOB(19)/BLOB(12) + prec=0x7fffffff(已通过 cmd=90/14 写入)
1081            let ct: i32 = if matches!(p, Param::Str(_)) { 19 } else { 12 };
1082                desc.extend_from_slice(&0i8.to_le_bytes());
1083                desc.extend_from_slice(&ct.to_le_bytes());
1084                desc.extend_from_slice(&0x7FFF_FFFFi32.to_le_bytes());
1085                desc.extend_from_slice(&0i32.to_le_bytes());
1086                encoders.push(Some(ParamEncoder::from_type(ct)));
1087            } else if let Some(sp) = server_params.and_then(|s| s.get(i)) {
1088                desc.extend_from_slice(&0i8.to_le_bytes());
1089                desc.extend_from_slice(&sp.col_type.to_le_bytes());
1090                desc.extend_from_slice(&sp.prec.to_le_bytes());
1091                desc.extend_from_slice(&sp.scale.to_le_bytes());
1092                encoders.push(Some(ParamEncoder::from_type(sp.col_type)));
1093            } else {
1094                let (ct, prec, scale, enc) = param_type(p, is_query, self.svr_encoding);
1095                desc.extend_from_slice(&0i8.to_le_bytes());
1096                desc.extend_from_slice(&ct.to_le_bytes());
1097                desc.extend_from_slice(&prec.to_le_bytes());
1098                desc.extend_from_slice(&scale.to_le_bytes());
1099                encoders.push(Some(enc));
1100            }
1101        }
1102
1103        // 参数数据
1104        let mut data = Vec::new();
1105        for group in &groups {
1106            for (i, p) in group.iter().enumerate() {
1107                if p.is_out() {
1108                    continue; // OUT 参数无数据
1109                }
1110                if p.is_null() {
1111                    data.extend_from_slice(&NULL_MARK.to_le_bytes());
1112                } else {
1113                    let enc = encoders
1114                        .get(i)
1115                        .and_then(|e| e.clone())
1116                        .unwrap_or_else(|| param_type(p, is_query, self.svr_encoding).3);
1117                    let raw = enc.encode(p, self.svr_encoding)?;
1118                    if lob_len(p, self.svr_encoding) >= 8188 {
1119                        data.extend_from_slice(&0u16.to_le_bytes()); // 大 LOB 已通过 cmd=90/14 写入
1120                    } else {
1121                        data.extend_from_slice(&(raw.len() as u16).to_le_bytes());
1122                        data.extend_from_slice(&raw);
1123                    }
1124                }
1125            }
1126        }
1127
1128        let mut body = desc;
1129        body.extend_from_slice(&data);
1130        self.send(CMD_BIND, &opts, &body, stmt)?;
1131        Ok(())
1132    }
1133
1134    fn write_lob_params(
1135        &mut self,
1136        stmt: i32,
1137        server_params: Option<&[ServerParam]>,
1138        params: &[Param],
1139    ) -> Result<()> {
1140        // 参数描述:小参数用 serverParams 类型;大值用 BLOB(12)/CLOB(19) + 0x7fffffff
1141        let mut desc = Vec::new();
1142        for (i, p) in params.iter().enumerate() {
1143            let raw_len = lob_len(p, self.svr_encoding);
1144            if raw_len >= 8188 {
1145                let ct: i32 = if matches!(p, Param::Str(_)) { 19 } else { 12 };
1146                desc.extend_from_slice(&0i8.to_le_bytes());
1147                desc.extend_from_slice(&ct.to_le_bytes());
1148                desc.extend_from_slice(&0x7FFF_FFFFi32.to_le_bytes());
1149                desc.extend_from_slice(&0i32.to_le_bytes());
1150            } else {
1151                let sp = server_params.and_then(|s| s.get(i));
1152                let ct = sp.map(|x| x.col_type).unwrap_or(2);
1153                let prec = sp.map(|x| x.prec).unwrap_or(0);
1154                let scale = sp.map(|x| x.scale).unwrap_or(0);
1155                desc.extend_from_slice(&0i8.to_le_bytes());
1156                desc.extend_from_slice(&ct.to_le_bytes());
1157                desc.extend_from_slice(&prec.to_le_bytes());
1158                desc.extend_from_slice(&scale.to_le_bytes());
1159            }
1160        }
1161        // cmd=90:LOB 参数声明(opts 帧20-21 = 参数个数)
1162        let mut opts90 = [0u8; 44];
1163        opts90[..2].copy_from_slice(&(params.len() as u16).to_le_bytes());
1164        self.send(90, &opts90, &desc, stmt)?;
1165        let f = self.read_frame()?;
1166        if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
1167            return Err(self.server_error(&f));
1168        }
1169        // cmd=14:分块写入每个大 LOB 参数(顺序与参数一致)
1170        for (i, p) in params.iter().enumerate() {
1171            if lob_len(p, self.svr_encoding) < 8188 {
1172                continue;
1173            }
1174            let data: Vec<u8> = match p {
1175                Param::Str(s) => self.encode_str(s),
1176                Param::Bytes(b) => b.clone(),
1177                _ => Vec::new(),
1178            };
1179            let mut opts14 = [0u8; 44];
1180            opts14[0] = i as u8; // 参数索引(0 基,Go: dm_build_665(..., icol, ...))
1181            let mut off = 0;
1182            while off < data.len() {
1183                let mut end = (off + self.lob_chunk_size).min(data.len());
1184                // 多字节编码字符边界对齐,避免分块切半导致乱码:
1185                // GB18030/EUC-KR:块末是首字节(0x81-0xFE)且下一字节是尾字节(0x40-0xFE)时回退;
1186                // UTF-8:下一字节是续字节(0x80-0xBF)时回退到字符起点
1187                if self.svr_encoding == GB18030 || self.svr_encoding == EUC_KR {
1188                    while end < data.len() && end > off
1189                        && (0x81..=0xFE).contains(&data[end - 1])
1190                        && (0x40..=0xFE).contains(&data[end])
1191                        && data[end] != 0x7F
1192                    {
1193                        end -= 1;
1194                    }
1195                } else {
1196                    while end < data.len() && end > off && (0x80..=0xBF).contains(&data[end]) {
1197                        end -= 1;
1198                    }
1199                }
1200                let chunk = &data[off..end];
1201                let mut body = Vec::with_capacity(8 + chunk.len());
1202                body.extend_from_slice(&(chunk.len() as i32).to_le_bytes());
1203                body.extend_from_slice(&(-1i32).to_le_bytes());
1204                body.extend_from_slice(chunk);
1205                self.send(14, &opts14, &body, stmt)?;
1206                let f = self.read_frame()?;
1207                if f.retcode != 0 && f.retcode != 111 && f.retcode != 100 {
1208                    return Err(self.server_error(&f));
1209                }
1210                off = end;
1211            }
1212        }
1213        Ok(())
1214    }
1215
1216    // ---------- 事务 ----------
1217
1218    /// 开始事务:设置隔离级别(cmd=52)+ 关闭自动提交(Go 实测顺序)
1219    pub fn begin(&mut self) -> Result<()> {
1220        self.send(52, &1i32.to_le_bytes(), &[], 0)?;
1221        let f = self.read_frame()?;
1222        self.check_ok(&f)?;
1223        self.auto_commit = false;
1224        self.in_transaction = true;
1225        Ok(())
1226    }
1227
1228    /// 提交事务(cmd=8)
1229    pub fn commit(&mut self) -> Result<()> {
1230        self.send(8, &[], &[], 0)?;
1231        let f = self.read_frame()?;
1232        self.check_ok(&f)?;
1233        self.auto_commit = true;
1234        self.in_transaction = false;
1235        Ok(())
1236    }
1237
1238    /// 回滚事务(cmd=9)
1239    pub fn rollback(&mut self) -> Result<()> {
1240        self.send(9, &[], &[], 0)?;
1241        let f = self.read_frame()?;
1242        self.check_ok(&f)?;
1243        self.auto_commit = true;
1244        self.in_transaction = false;
1245        Ok(())
1246    }
1247
1248    /// 设置事务隔离级别(cmd=52):1=读已提交 2=可重复读 3=串行化
1249    pub fn set_iso_level(&mut self, level: i32) -> Result<()> {
1250        self.send(52, &level.to_le_bytes(), &[], 0)?;
1251        let f = self.read_frame()?;
1252        self.check_ok(&f)?;
1253        Ok(())
1254    }
1255
1256    pub fn close(&mut self) {
1257        self.reader = None;
1258    }
1259
1260    /// 用服务器编码编码字符串(SQL 文本 / 字符串参数 / CLOB 写入)。
1261    fn encode_str(&self, s: &str) -> Vec<u8> {
1262        enc_str(self.svr_encoding, s)
1263    }
1264
1265    /// 用服务器编码解码(错误消息等),损坏字节替换为 U+FFFD。
1266    fn decode_lossy(&self, b: &[u8]) -> String {
1267        let (s, _, _) = self.svr_encoding.decode(b);
1268        s.into_owned()
1269    }
1270}
1271
1272// ---------- 工具函数 ----------
1273
1274pub(crate) fn is_query_sql(sql: &str) -> bool {
1275    let s = sql.trim_start();
1276    let up = s.to_ascii_uppercase();
1277    up.starts_with("SELECT")
1278        || up.starts_with("WITH")
1279        || up.starts_with("DESC")
1280        || up.starts_with("SHOW")
1281}
1282
1283/// 按指定服务器编码编码字符串(SQL 文本 / 字符串参数 / CLOB 写入)。
1284pub(crate) fn enc_str(enc: &'static Encoding, s: &str) -> Vec<u8> {
1285    enc.encode(s).0.into_owned()
1286}
1287
1288/// 参数值字节长度(str 按服务器编码;bytes 原长)
1289pub(crate) fn lob_len(p: &Param, enc: &'static Encoding) -> usize {
1290    match p {
1291        Param::Str(s) => enc_str(enc, s).len(),
1292        Param::Bytes(b) => b.len(),
1293        _ => 0,
1294    }
1295}
1296
1297/// 参数类型猜测 → (colType, prec, scale, 编码器),对照 Go 驱动实测:
1298/// int→INT(7)/prec4, str→VARCHAR(2)/prec=len, float→DOUBLE(11)/prec8,
1299/// date→DATE(14)/prec3, None→NULL
1300/// 带时区(timezone_minutes=Some)自动升为 TZ 类型:TIME_TZ(22)/DATETIME_TZ(23)
1301fn param_type(p: &Param, is_query: bool, enc: &'static Encoding) -> (i32, i32, i32, ParamEncoder) {
1302    match p {
1303        Param::Bool(_) => (7, 4, 0, ParamEncoder::Int),
1304        Param::Int(_) => {
1305            // 查询参数用 BIGINT(8)/prec8(Go 实测),写入用 INT(7)/prec4
1306            if is_query {
1307                (8, 8, 0, ParamEncoder::BigInt)
1308            } else {
1309                (7, 4, 0, ParamEncoder::Int)
1310            }
1311        }
1312        Param::Float(_) => (11, 8, 0, ParamEncoder::Double),
1313        Param::Date(_) => (14, 3, 0, ParamEncoder::Date),
1314        Param::DateTime(dt) => {
1315            if dt.time.timezone_minutes.is_some() {
1316                (23, 8, 0, ParamEncoder::DateTimeTz)
1317            } else {
1318                (16, 8, 0, ParamEncoder::DateTime)
1319            }
1320        }
1321        Param::Time(t) => {
1322            if t.timezone_minutes.is_some() {
1323                (22, 5, 0, ParamEncoder::TimeTz)
1324            } else {
1325                (15, 5, 0, ParamEncoder::Time)
1326            }
1327        }
1328        Param::Bytes(b) => (17, b.len() as i32, 0, ParamEncoder::Bytes),
1329        Param::Str(s) => {
1330            let len = enc_str(enc, s).len();
1331            // 查询参数 prec=8188(0x1FFC);写入参数 prec=列长度(用 50 或实际长度)
1332            let prec = if is_query { 8188 } else { 50.max(len as i32) };
1333            (2, prec, 0, ParamEncoder::Str)
1334        }
1335        Param::Null => {
1336            // NULL 参数:VARCHAR(2)/prec=8188
1337            (2, 8188, 0, ParamEncoder::Str)
1338        }
1339        Param::Out(_) => (2, 0, 0, ParamEncoder::Str),
1340    }
1341}
1342
1343fn out_type_hint(hint: Option<OutType>) -> i32 {
1344    match hint {
1345        Some(OutType::Bool) => 13,
1346        Some(OutType::Int) => 8,
1347        Some(OutType::Float) => 11,
1348        Some(OutType::Str) => 2,
1349        Some(OutType::Date) => 14,
1350        Some(OutType::DateTime) => 16,
1351        None => 2,
1352    }
1353}
1354
1355fn out_type_prec(hint: Option<OutType>) -> i32 {
1356    match hint {
1357        Some(OutType::Int) => 8,
1358        Some(OutType::Str) => 32767,
1359        Some(OutType::DateTime) => 8,
1360        Some(OutType::Date) => 3,
1361        _ => 8,
1362    }
1363}
1364
1365/// 解析 cmd=5 响应(DML prepare)的 serverParams。
1366pub fn parse_server_params(body: &[u8]) -> Vec<ServerParam> {
1367    let mut params = Vec::new();
1368    let n = body.len();
1369    let mut pos = 0usize;
1370    while pos + 31 <= n {
1371        let col_type = le_i32(body, pos);
1372        let prec = le_i32(body, pos + 4);
1373        let scale = le_i32(body, pos + 8);
1374        pos += 16;
1375        if pos + 2 > n {
1376            break;
1377        }
1378        pos += 2; // itemFlag
1379        pos += 4; // 跳过
1380        if pos + 2 > n {
1381            break;
1382        }
1383        let io_type = body[pos] as i32;
1384        pos += 2; // ioType 是 int16(Go: int8(Dm_build_204()),消耗 2 字节)
1385        if pos + 8 > n {
1386            break;
1387        }
1388        let nlen = i16::from_le_bytes(body[pos..pos + 2].try_into().unwrap());
1389        let tlen = i16::from_le_bytes(body[pos + 2..pos + 4].try_into().unwrap());
1390        let tblen = i16::from_le_bytes(body[pos + 4..pos + 6].try_into().unwrap());
1391        let slen = i16::from_le_bytes(body[pos + 6..pos + 8].try_into().unwrap());
1392        pos += 8;
1393        let total = (nlen + tlen + tblen + slen) as i64;
1394        if pos + total as usize > n {
1395            break;
1396        }
1397        pos += total as usize;
1398        params.push(ServerParam { col_type, prec, scale, io_type });
1399        // 名称描述完后通常还有 baseName 或尾部;用"合理 colType"判断终止
1400        if !(0..=40).contains(&col_type) {
1401            break;
1402        }
1403    }
1404    params
1405}
1406
1407/// 按服务器参数类型返回编码器(serverParams 优先于类型猜测)
1408#[derive(Debug, Clone, PartialEq)]
1409enum ParamEncoder {
1410    Str,
1411    TinyInt,
1412    SmallInt,
1413    Int,
1414    BigInt,
1415    Real,
1416    Double,
1417    Bool,
1418    Date,
1419    Time,
1420    TimeTz,
1421    DateTime,
1422    DateTimeTz,
1423    DateTime2,
1424    DateTime2Tz,
1425    Bytes,
1426}
1427
1428impl ParamEncoder {
1429    fn from_type(col_type: i32) -> Self {
1430        match col_type {
1431            0 | 1 | 2 | 19 => ParamEncoder::Str, // CHAR/VARCHAR2/VARCHAR/CLOB
1432            5 => ParamEncoder::TinyInt,
1433            6 => ParamEncoder::SmallInt,
1434            7 => ParamEncoder::Int,
1435            8 => ParamEncoder::BigInt,
1436            10 => ParamEncoder::Real,
1437            11 => ParamEncoder::Double,
1438            13 => ParamEncoder::Bool,
1439            14 => ParamEncoder::Date,
1440            15 => ParamEncoder::Time,
1441            22 => ParamEncoder::TimeTz, // TIME_TZ
1442            16 => ParamEncoder::DateTime,
1443            23 => ParamEncoder::DateTimeTz, // DATETIME_TZ
1444            26 => ParamEncoder::DateTime2,  // DATETIME2
1445            27 => ParamEncoder::DateTime2Tz, // DATETIME2_TZ
1446            12 | 17 | 18 => ParamEncoder::Bytes, // BLOB/BINARY/VARBINARY
1447            _ => ParamEncoder::Str,
1448        }
1449    }
1450
1451    fn encode(&self, p: &Param, enc: &'static Encoding) -> Result<Vec<u8>> {
1452        match self {
1453            ParamEncoder::Str => match p {
1454                Param::Str(s) => Ok(enc_str(enc, s)),
1455                Param::Bytes(b) => Ok(b.clone()),
1456                _ => Ok(enc_str(enc, &to_string_value(p))),
1457            },
1458            ParamEncoder::TinyInt => Ok((to_i64(p)? as i8).to_le_bytes().to_vec()),
1459            ParamEncoder::SmallInt => Ok((to_i64(p)? as i16).to_le_bytes().to_vec()),
1460            ParamEncoder::Int => Ok((to_i64(p)? as i32).to_le_bytes().to_vec()),
1461            ParamEncoder::BigInt => Ok(to_i64(p)?.to_le_bytes().to_vec()),
1462            ParamEncoder::Real => Ok((to_f64(p)? as f32).to_le_bytes().to_vec()),
1463            ParamEncoder::Double => Ok(to_f64(p)?.to_le_bytes().to_vec()),
1464            ParamEncoder::Bool => Ok(vec![if to_bool(p) { 1 } else { 0 }]),
1465            ParamEncoder::Date => Ok(encode_date(&to_date(p)?).to_vec()),
1466            ParamEncoder::Time => Ok(encode_time(&to_time(p)?).to_vec()),
1467            ParamEncoder::TimeTz => Ok(encode_time_tz(&to_time(p)?)),
1468            ParamEncoder::DateTime => Ok(encode_datetime(&to_datetime(p)?)),
1469            ParamEncoder::DateTimeTz => Ok(encode_datetime_tz(&to_datetime(p)?)),
1470            ParamEncoder::DateTime2 => Ok(encode_datetime2(&to_datetime(p)?)),
1471            ParamEncoder::DateTime2Tz => Ok(encode_datetime2_tz(&to_datetime(p)?)),
1472            ParamEncoder::Bytes => match p {
1473                Param::Bytes(b) => Ok(b.clone()),
1474                _ => Ok(to_string_value(p).into_bytes()),
1475            },
1476        }
1477    }
1478}
1479
1480fn to_i64(p: &Param) -> Result<i64> {
1481    match p {
1482        Param::Int(v) => Ok(*v),
1483        Param::Bool(b) => Ok(*b as i64),
1484        Param::Float(f) => Ok(*f as i64),
1485        Param::Str(s) => s.trim().parse::<i64>().map_err(|_| DmError::arg(format!("无法将 '{s}' 转为整数"))),
1486        Param::Null => Ok(0),
1487        _ => Err(DmError::arg(format!("无法将 {p:?} 转为整数"))),
1488    }
1489}
1490
1491fn to_f64(p: &Param) -> Result<f64> {
1492    match p {
1493        Param::Float(f) => Ok(*f),
1494        Param::Int(v) => Ok(*v as f64),
1495        Param::Bool(b) => Ok((*b as i64) as f64),
1496        Param::Str(s) => s.trim().parse::<f64>().map_err(|_| DmError::arg(format!("无法将 '{s}' 转为浮点"))),
1497        _ => Err(DmError::arg(format!("无法将 {p:?} 转为浮点"))),
1498    }
1499}
1500
1501fn to_bool(p: &Param) -> bool {
1502    match p {
1503        Param::Bool(b) => *b,
1504        Param::Int(v) => *v != 0,
1505        Param::Float(f) => *f != 0.0,
1506        Param::Str(s) => !s.is_empty() && s != "0" && !s.eq_ignore_ascii_case("false"),
1507        _ => false,
1508    }
1509}
1510
1511fn to_date(p: &Param) -> Result<DmDate> {
1512    match p {
1513        Param::Date(d) => Ok(*d),
1514        Param::DateTime(dt) => Ok(dt.date),
1515        Param::Str(s) => parse_date_str(s),
1516        _ => Err(DmError::arg(format!("无法将 {p:?} 转为日期"))),
1517    }
1518}
1519
1520fn to_time(p: &Param) -> Result<DmTime> {
1521    match p {
1522        Param::Time(t) => Ok(*t),
1523        Param::DateTime(dt) => Ok(dt.time),
1524        Param::Str(s) => parse_time_str(s),
1525        _ => Err(DmError::arg(format!("无法将 {p:?} 转为时间"))),
1526    }
1527}
1528
1529fn to_datetime(p: &Param) -> Result<DmDateTime> {
1530    match p {
1531        Param::DateTime(dt) => Ok(*dt),
1532        Param::Date(d) => Ok(DmDateTime::new(*d, DmTime::new(0, 0, 0, 0))),
1533        Param::Str(s) => {
1534            // 兼容 "YYYY-MM-DD HH:MM:SS[.ffffff]" 与纯日期
1535            let d = parse_date_str(&s[..s.len().min(10)])?;
1536            let t = if s.len() > 10 {
1537                parse_time_str(&s[11..])?
1538            } else {
1539                DmTime::new(0, 0, 0, 0)
1540            };
1541            Ok(DmDateTime::new(d, t))
1542        }
1543        _ => Err(DmError::arg(format!("无法将 {p:?} 转为日期时间"))),
1544    }
1545}
1546
1547fn to_string_value(p: &Param) -> String {
1548    match p {
1549        Param::Str(s) => s.clone(),
1550        Param::Int(v) => v.to_string(),
1551        Param::Float(f) => f.to_string(),
1552        Param::Bool(b) => b.to_string(),
1553        Param::Date(d) => d.to_string(),
1554        Param::Time(t) => t.to_string(),
1555        Param::DateTime(dt) => dt.to_string(),
1556        Param::Bytes(b) => String::from_utf8_lossy(b).into_owned(),
1557        Param::Null => "".to_string(),
1558        Param::Out(_) => "".to_string(),
1559    }
1560}
1561
1562/// 解析 "YYYY-MM-DD"
1563fn parse_date_str(s: &str) -> Result<DmDate> {
1564    let parts: Vec<&str> = s.trim().split('-').collect();
1565    if parts.len() != 3 {
1566        return Err(DmError::arg(format!("日期格式错误: '{s}'")));
1567    }
1568    let year: i32 = parts[0].parse().map_err(|_| DmError::arg(format!("日期格式错误: '{s}'")))?;
1569    let month: u8 = parts[1].parse().map_err(|_| DmError::arg(format!("日期格式错误: '{s}'")))?;
1570    let day: u8 = parts[2].parse().map_err(|_| DmError::arg(format!("日期格式错误: '{s}'")))?;
1571    Ok(DmDate::new(year, month, day))
1572}
1573
1574/// 解析 "HH:MM:SS[.ffffff]"
1575fn parse_time_str(s: &str) -> Result<DmTime> {
1576    let s = s.trim();
1577    let (hms, frac) = match s.split_once('.') {
1578        Some((h, f)) => (h, Some(f)),
1579        None => (s, None),
1580    };
1581    let parts: Vec<&str> = hms.split(':').collect();
1582    if parts.len() < 2 {
1583        return Err(DmError::arg(format!("时间格式错误: '{s}'")));
1584    }
1585    let hour: u8 = parts[0].parse().map_err(|_| DmError::arg(format!("时间格式错误: '{s}'")))?;
1586    let minute: u8 = parts[1].parse().map_err(|_| DmError::arg(format!("时间格式错误: '{s}'")))?;
1587    let second: u8 = if parts.len() > 2 { parts[2].parse().map_err(|_| DmError::arg(format!("时间格式错误: '{s}'")))? } else { 0 };
1588    let microsecond: u32 = match frac {
1589        Some(f) => {
1590            let mut f = f.to_string();
1591            while f.len() < 6 {
1592                f.push('0');
1593            }
1594            f[..6].parse().unwrap_or(0)
1595        }
1596        None => 0,
1597    };
1598    Ok(DmTime::new(hour, minute, second, microsecond))
1599}
1600
1601fn le_i32(b: &[u8], pos: usize) -> i32 {
1602    i32::from_le_bytes(b[pos..pos + 4].try_into().unwrap())
1603}
1604
1605fn le_u16(b: &[u8], pos: usize) -> u16 {
1606    u16::from_le_bytes(b[pos..pos + 2].try_into().unwrap())
1607}
1608
1609fn le_i64(b: &[u8], pos: usize) -> i64 {
1610    i64::from_le_bytes(b[pos..pos + 8].try_into().unwrap())
1611}
1612
1613fn parse_bigint_hex(hex: &str) -> num_bigint::BigUint {
1614    num_bigint::BigUint::parse_bytes(hex.as_bytes(), 16).expect("hex 解析失败")
1615}
1616
1617fn hex(b: &[u8]) -> String {
1618    b.iter().map(|x| format!("{x:02x}")).collect()
1619}
1620
1621#[cfg(test)]
1622mod tests {
1623    use super::*;
1624
1625    #[test]
1626    fn is_query_detection() {
1627        assert!(is_query_sql("  SELECT * FROM t"));
1628        assert!(is_query_sql("WITH x AS (...) SELECT 1"));
1629        assert!(is_query_sql("DESC t"));
1630        assert!(is_query_sql("SHOW TABLES"));
1631        assert!(!is_query_sql("INSERT INTO t VALUES (1)"));
1632        assert!(!is_query_sql("CALL proc(1)"));
1633        assert!(!is_query_sql("UPDATE t SET a=1"));
1634    }
1635
1636    #[test]
1637    fn param_type_guess() {
1638        let (ct, prec, scale, enc) = param_type(&Param::Int(1), true, GB18030);
1639        assert_eq!((ct, prec, scale), (8, 8, 0));
1640        assert_eq!(enc.encode(&Param::Int(1), GB18030).unwrap(), 1i64.to_le_bytes());
1641
1642        let (ct, prec, scale, _) = param_type(&Param::Int(1), false, GB18030);
1643        assert_eq!((ct, prec, scale), (7, 4, 0));
1644
1645        let (ct, prec, _, _) = param_type(&Param::Str("测试".into()), false, GB18030);
1646        assert_eq!(ct, 2);
1647        assert_eq!(prec, 50); // GB18030 8 字节 < 50
1648
1649        // UTF-8 下 "测试" 6 字节,仍 < 50
1650        let (ct, prec, _, _) = param_type(&Param::Str("测试".into()), false, UTF_8);
1651        assert_eq!(ct, 2);
1652        assert_eq!(prec, 50);
1653
1654        // UTF-8 下超长字符串按字节长计算 prec(区别于 GB18030 的字节长)
1655        let s = "中".repeat(30); // UTF-8 90 字节
1656        let (_ct, prec, _, _) = param_type(&Param::Str(s.clone()), false, UTF_8);
1657        assert_eq!(prec, 90);
1658        let (_ct, prec, _, _) = param_type(&Param::Str(s.clone()), false, GB18030);
1659        assert_eq!(prec, 60); // GB18030 60 字节
1660
1661        let (_ct, prec, _, _) = param_type(&Param::Str("x".repeat(100).as_str().into()), false, GB18030);
1662        assert_eq!(prec, 100);
1663
1664        let (ct, prec, _, _) = param_type(&Param::Str("x".into()), true, GB18030);
1665        assert_eq!(ct, 2);
1666        assert_eq!(prec, 8188);
1667
1668        // 带时区:TIME_TZ(22)/DATETIME_TZ(23)
1669        let mut tt = DmTime::new(12, 34, 56, 0);
1670        tt.timezone_minutes = Some(480);
1671        let (ct, prec, scale, enc) = param_type(&Param::Time(tt), false, GB18030);
1672        assert_eq!((ct, prec, scale), (22, 5, 0));
1673        assert_eq!(enc.encode(&Param::Time(tt), GB18030).unwrap(), encode_time_tz(&tt));
1674
1675        let mut dtz = DmDateTime::new(DmDate::new(2026, 8, 14), DmTime::new(12, 34, 56, 0));
1676        dtz.time.timezone_minutes = Some(480);
1677        let (ct, prec, scale, enc) = param_type(&Param::DateTime(dtz), false, GB18030);
1678        assert_eq!((ct, prec, scale), (23, 8, 0));
1679        assert_eq!(enc.encode(&Param::DateTime(dtz), GB18030).unwrap(), encode_datetime_tz(&dtz));
1680
1681        // 无时区保持普通类型
1682        let (ct, _, _, _) = param_type(&Param::Time(DmTime::new(1, 2, 3, 0)), false, GB18030);
1683        assert_eq!(ct, 15);
1684        let (ct, _, _, _) = param_type(&Param::DateTime(DmDateTime::new(DmDate::new(2026, 1, 1), DmTime::new(0, 0, 0, 0))), false, GB18030);
1685        assert_eq!(ct, 16);
1686        let (ct, _, _, _) = param_type(&Param::Date(DmDate::new(2026, 8, 12)), false, GB18030);
1687        assert_eq!(ct, 14);
1688        let (ct, _, _, _) = param_type(&Param::Float(1.5), false, GB18030);
1689        assert_eq!(ct, 11);
1690        let (ct, _, _, _) = param_type(&Param::Bytes(vec![1, 2]), false, GB18030);
1691        assert_eq!(ct, 17);
1692        let (ct, _, _, _) = param_type(&Param::Bool(true), false, GB18030);
1693        assert_eq!(ct, 7);
1694        let (ct, _, _, _) = param_type(&Param::Null, false, GB18030);
1695        assert_eq!(ct, 2);
1696    }
1697
1698    #[test]
1699    fn encoding_resolve_and_length() {
1700        // 编码名解析(不区分大小写)
1701        assert_eq!(resolve_encoding(None), None);
1702        assert_eq!(resolve_encoding(Some("")), None);
1703        assert_eq!(resolve_encoding(Some("utf-8")), Some(UTF_8));
1704        assert_eq!(resolve_encoding(Some("UTF8")), Some(UTF_8));
1705        assert_eq!(resolve_encoding(Some("gb18030")), Some(GB18030));
1706        assert_eq!(resolve_encoding(Some("GBK")), Some(GB18030));
1707        assert_eq!(resolve_encoding(Some("euc-kr")), Some(EUC_KR));
1708        assert_eq!(resolve_encoding(Some("latin1")), None); // 未识别 → 自动检测
1709
1710        // 编码字节长度:UTF-8 中文 3 字节/字,GB18030 2 字节/字
1711        let s = "中文测试";
1712        assert_eq!(enc_str(UTF_8, s).len(), 12);
1713        assert_eq!(enc_str(GB18030, s).len(), 8);
1714        assert_eq!(lob_len(&Param::Str(s.into()), UTF_8), 12);
1715        assert_eq!(lob_len(&Param::Str(s.into()), GB18030), 8);
1716
1717        // 握手响应编码码值映射(Go 驱动逻辑:1=UTF8, 2=EUCKR, 其他=GB18030)
1718        fn detect(opts: &[u8]) -> &'static Encoding {
1719            let code = i32::from_le_bytes(opts[8..12].try_into().unwrap());
1720            match code {
1721                1 => UTF_8,
1722                2 => EUC_KR,
1723                _ => GB18030,
1724            }
1725        }
1726        let mut opts = [0u8; 44];
1727        assert_eq!(detect(&opts), GB18030); // 0 → GB18030
1728        opts[8..12].copy_from_slice(&1i32.to_le_bytes());
1729        assert_eq!(detect(&opts), UTF_8);
1730        opts[8..12].copy_from_slice(&2i32.to_le_bytes());
1731        assert_eq!(detect(&opts), EUC_KR);
1732    }
1733
1734    #[test]
1735    fn utf8_char_boundary_align() {
1736        // UTF-8 分块对齐:块末若切在续字节则回退到字符起点
1737        let s = "一二三四五六七八九十"; // 30 字节 UTF-8
1738        let data = enc_str(UTF_8, s);
1739        let mut end = 7usize.min(data.len()); // 切在 "三" 中间(字节 6-8)
1740        while end < data.len() && end > 0 && (0x80..=0xBF).contains(&data[end]) {
1741            end -= 1;
1742        }
1743        assert_eq!(end, 6);
1744        assert_eq!(&data[..end], "一二".as_bytes());
1745    }
1746
1747    #[test]
1748    fn server_params_parse() {
1749        // 抓包实测:INSERT INTO lob_test3 (id, data) VALUES (?, ?) 的 prepare 响应 (cmd=0 len=72)
1750        let body = hex2b(
1751            "0700000004000000000000000100000000000000000000000000030000000000494e5413000000ffffff7f000000000100000000000000000000000000040000000000434c4f4200",
1752        );
1753        let params = parse_server_params(&body);
1754        assert_eq!(params.len(), 2);
1755        assert_eq!(params[0].col_type, 7);
1756        assert_eq!(params[0].prec, 4);
1757        assert_eq!(params[0].scale, 0);
1758        assert_eq!(params[1].col_type, 19); // CLOB
1759        assert_eq!(params[1].prec, 0x7FFF_FFFF);
1760    }
1761
1762    fn hex2b(s: &str) -> Vec<u8> {
1763        (0..s.len())
1764            .step_by(2)
1765            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
1766            .collect()
1767    }
1768
1769    #[test]
1770    fn execute_opts_match_capture() {
1771        // 非参数化 SELECT 抓包实测:01 01 00 01 00 00 00 ff ff ff ff ff ff ff 7f 00 00 00 01
1772        let c = DmClient::new("h", 1, "u", "p");
1773        let o = c.execute_opts(false);
1774        assert_eq!(
1775            &o[..19],
1776            &[
1777                0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1778                0xff, 0x7f, 0x00, 0x00, 0x00, 0x01
1779            ]
1780        );
1781        // 参数化 SQL 抓包实测:01 00 00 01 00 00 00 ff ff ff ff ff ff ff 7f 00 00 00 00
1782        let o = c.execute_opts(true);
1783        assert_eq!(
1784            &o[..19],
1785            &[
1786                0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1787                0xff, 0x7f, 0x00, 0x00, 0x00, 0x00
1788            ]
1789        );
1790    }
1791
1792    #[test]
1793    fn bind_opts_match_capture() {
1794        // 抓包实测 cmd=13 参数区(1 参数 batch=1):
1795        // 01 01 00 01 01 00 00 00 ... ff ff ff ff ff ff ff 7f 01 00 00 00 ff ff ff ff
1796        let mut c = DmClient::new("h", 1, "u", "p");
1797        c.auto_commit = true;
1798        let params = [Param::Int(1)];
1799        // 直接构造 opts 校验(通过 bind_params 无法断言,这里独立复现)
1800        let mut opts = [0u8; 44];
1801        opts[0] = 1;
1802        opts[1..3].copy_from_slice(&1u16.to_le_bytes());
1803        opts[3] = 1;
1804        opts[4..12].copy_from_slice(&1i64.to_le_bytes());
1805        opts[20..28].copy_from_slice(&i64::MAX.to_le_bytes());
1806        opts[28] = 1;
1807        opts[32..36].copy_from_slice(&(-1i32).to_le_bytes());
1808        assert_eq!(&opts[0..12], &[0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1809        assert_eq!(&opts[20..36], &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
1810        let _ = &params;
1811    }
1812
1813    #[test]
1814    fn date_str_parse() {
1815        let d = parse_date_str("2026-08-12").unwrap();
1816        assert_eq!(d, DmDate::new(2026, 8, 12));
1817        let t = parse_time_str("12:34:56.789").unwrap();
1818        assert_eq!(t, DmTime::new(12, 34, 56, 789000));
1819        let dt = to_datetime(&Param::Str("2030-06-15 08:09:10.111222".into())).unwrap();
1820        assert_eq!(dt, DmDateTime::new(DmDate::new(2030, 6, 15), DmTime::new(8, 9, 10, 111222)));
1821    }
1822}