Skip to main content

dm_pure/
result.rs

1//! 达梦结果集解析:列描述符 + 行数据 + 类型解码(对照 Go 驱动 + 抓包实测格式)。
2
3use encoding_rs::Encoding;
4
5use crate::Result;
6
7// 达梦类型常量(zzn.go)
8pub const DM_CHAR: i32 = 0;
9pub const DM_VARCHAR2: i32 = 1;
10pub const DM_VARCHAR: i32 = 2;
11pub const DM_BIT: i32 = 3;
12pub const DM_TINYINT: i32 = 5;
13pub const DM_SMALLINT: i32 = 6;
14pub const DM_INT: i32 = 7;
15pub const DM_BIGINT: i32 = 8;
16pub const DM_DECIMAL: i32 = 9;
17pub const DM_REAL: i32 = 10;
18pub const DM_DOUBLE: i32 = 11;
19pub const DM_BLOB: i32 = 12;
20pub const DM_BOOLEAN: i32 = 13;
21pub const DM_DATE: i32 = 14;
22pub const DM_TIME: i32 = 15;
23pub const DM_DATETIME: i32 = 16;
24pub const DM_BINARY: i32 = 17;
25pub const DM_VARBINARY: i32 = 18;
26pub const DM_CLOB: i32 = 19;
27pub const DM_INTERVAL_YM: i32 = 20;
28pub const DM_INTERVAL_DT: i32 = 21;
29pub const DM_TIME_TZ: i32 = 22;
30pub const DM_DATETIME_TZ: i32 = 23;
31pub const DM_XDEC_INT32: i32 = 24;
32pub const DM_XDEC_INT64: i32 = 25;
33pub const DM_DATETIME2: i32 = 26;
34pub const DM_DATETIME2_TZ: i32 = 27;
35// (对照 Go 驱动 zzn.go:TIME_TZ=22, DATETIME_TZ=23, XDEC_INT32=24, XDEC_INT64=25,
36//  DATETIME2=26, DATETIME2_TZ=27;旧版误写 DATETIME2=30 已修正)
37
38/// 行数据 NULL 标记
39pub const NULL_MARK: u16 = 0xFFFE;
40/// LOB/特殊标记(0xFFFF 后跟 int32 真实长度 + 数据,Go zzo.go convertBytes2BaseData)
41pub const LOB_MARK: u16 = 0xFFFF;
42
43/// 达梦日期(年可为负/超 9999,避免 chrono/NaiveDate 限制)
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct DmDate {
46    pub year: i32,
47    pub month: u8,
48    pub day: u8,
49}
50
51impl DmDate {
52    pub fn new(year: i32, month: u8, day: u8) -> Self {
53        DmDate { year, month, day }
54    }
55}
56
57impl std::fmt::Display for DmDate {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
60    }
61}
62
63/// 达梦时间(微秒精度)。`timezone_minutes` 为带时区类型(TIME_TZ)的偏移(分钟,可负)。
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct DmTime {
66    pub hour: u8,
67    pub minute: u8,
68    pub second: u8,
69    pub microsecond: u32,
70    /// 时区偏移(分钟,东正西负);非 TZ 类型为 None
71    pub timezone_minutes: Option<i16>,
72}
73
74impl DmTime {
75    pub fn new(hour: u8, minute: u8, second: u8, microsecond: u32) -> Self {
76        DmTime { hour, minute, second, microsecond, timezone_minutes: None }
77    }
78}
79
80fn fmt_tz(tz: i16) -> String {
81    let sign = if tz < 0 { "-" } else { "+" };
82    let a = tz.unsigned_abs() as i32;
83    format!("{sign}{:02}:{:02}", a / 60, a % 60)
84}
85
86impl std::fmt::Display for DmTime {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        write!(
89            f,
90            "{:02}:{:02}:{:02}.{:06}",
91            self.hour, self.minute, self.second, self.microsecond
92        )?;
93        if let Some(tz) = self.timezone_minutes {
94            write!(f, " {}", fmt_tz(tz))?;
95        }
96        Ok(())
97    }
98}
99
100/// 达梦日期时间。`time.timezone_minutes` 为带时区类型(DATETIME_TZ/DATETIME2_TZ)的偏移。
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct DmDateTime {
103    pub date: DmDate,
104    pub time: DmTime,
105}
106
107impl DmDateTime {
108    pub fn new(date: DmDate, time: DmTime) -> Self {
109        DmDateTime { date, time }
110    }
111}
112
113impl std::fmt::Display for DmDateTime {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        write!(f, "{} {}", self.date, self.time)
116    }
117}
118
119/// 解码后的单元格值。
120#[derive(Debug, Clone, PartialEq)]
121pub enum Value {
122    Null,
123    Bool(bool),
124    TinyInt(i8),
125    SmallInt(i16),
126    Int(i32),
127    BigInt(i64),
128    Real(f32),
129    Double(f64),
130    /// DECIMAL 保持字符串,避免精度丢失(如 DECIMAL(38))
131    Decimal(String),
132    Str(String),
133    Bytes(Vec<u8>),
134    Date(DmDate),
135    Time(DmTime),
136    DateTime(DmDateTime),
137    Interval(String),
138    /// 未识别的原始字节
139    Raw(Vec<u8>),
140}
141
142impl Value {
143    pub fn as_str(&self) -> Option<&str> {
144        match self {
145            Value::Str(s) => Some(s),
146            _ => None,
147        }
148    }
149    pub fn as_i64(&self) -> Option<i64> {
150        match self {
151            Value::Int(v) => Some(*v as i64),
152            Value::BigInt(v) => Some(*v),
153            Value::SmallInt(v) => Some(*v as i64),
154            Value::TinyInt(v) => Some(*v as i64),
155            Value::Bool(b) => Some(*b as i64),
156            Value::Double(f) => Some(*f as i64),
157            Value::Real(f) => Some(*f as i64),
158            _ => None,
159        }
160    }
161    pub fn as_f64(&self) -> Option<f64> {
162        match self {
163            Value::Double(f) => Some(*f),
164            Value::Real(f) => Some(*f as f64),
165            Value::Int(v) => Some(*v as f64),
166            Value::BigInt(v) => Some(*v as f64),
167            _ => None,
168        }
169    }
170    pub fn as_bytes(&self) -> Option<&[u8]> {
171        match self {
172            Value::Bytes(b) => Some(b),
173            Value::Raw(b) => Some(b),
174            _ => None,
175        }
176    }
177}
178
179/// 列描述符。
180#[derive(Debug, Clone, PartialEq)]
181pub struct Column {
182    pub col_type: i32,
183    pub prec: i32,
184    pub scale: i32,
185    pub nullable: bool,
186    pub name: String,
187    pub type_name: String,
188    pub table_name: String,
189    pub schema_name: String,
190    pub lob: bool,
191}
192
193/// 原始行:每单元格为 Some(bytes) 或 None(NULL)。
194pub type Row = Vec<Option<Vec<u8>>>;
195
196fn le_i32(b: &[u8], pos: usize) -> i32 {
197    i32::from_le_bytes(b[pos..pos + 4].try_into().unwrap())
198}
199
200fn le_u16(b: &[u8], pos: usize) -> u16 {
201    u16::from_le_bytes(b[pos..pos + 2].try_into().unwrap())
202}
203
204fn read_str_at(body: &[u8], pos: &mut usize, len: usize, enc: &'static Encoding) -> String {
205    if *pos + len > body.len() {
206        *pos = body.len();
207        return String::new();
208    }
209    let (s, _, _) = enc.decode(&body[*pos..*pos + len]);
210    *pos += len;
211    s.into_owned()
212}
213
214/// 列描述符定位自适应(服务器参数回显区长度不固定)。
215///
216/// 实测:服务器在 DDL(DROP/CREATE)后首条参数化查询的参数回显区会多带 8B 类型名
217/// (如 "BIGINT"),列描述符起点从 `32*n` 变为 `32*n+8`;硬编码 `params.len()*32`
218/// 会解析错位成垃圾 col_type(如 1229408578)。
219/// 依次尝试 32/32+8/16/16+8/0 字节每参数偏移,取能解析出合法列描述符
220/// (列数匹配、col_type 0..=40、prec 合理、列名非空且含可打印字符)的候选。
221pub fn parse_cols_robust(
222    body: &[u8],
223    n_params: usize,
224    ncols: usize,
225    enc: &'static Encoding,
226) -> Result<Vec<Column>> {
227    let valid = |cols: &[Column]| -> bool {
228        if cols.len() != ncols {
229            return false;
230        }
231        for c in cols {
232            if !(0..=40).contains(&c.col_type) {
233                return false;
234            }
235            if !(0..=1_000_000).contains(&c.prec) {
236                return false;
237            }
238            if c.name.is_empty()
239                || c.name.chars().any(|ch| ch.is_control())
240                || !c.name.chars().any(|ch| ch.is_alphanumeric())
241            {
242                return false;
243            }
244        }
245        true
246    };
247    for (per, off) in [(32usize, 0i32), (32, 8), (16, 0), (16, 8), (0, 0), (32, -8), (16, -8)] {
248        let pos = (n_params * per) as i64 + off as i64;
249        if pos < 0 || pos + 30 > body.len() as i64 {
250            continue;
251        }
252        if let Ok((cols, _)) = parse_columns(body, pos as usize, ncols, enc) {
253            if valid(&cols) {
254                return Ok(cols);
255            }
256        }
257    }
258    // 全范围扫描兜底(每 2 字节步进,应对非常规回显如 32*n+10 等)
259    let scan_end = body.len().saturating_sub(30).min(256);
260    for pos in (0..scan_end).step_by(2) {
261        if let Ok((cols, _)) = parse_columns(body, pos, ncols, enc) {
262            if valid(&cols) {
263                return Ok(cols);
264            }
265        }
266    }
267    // 最后兜底:按 32B/参数
268    let (cols, _) = parse_columns(body, n_params * 32, ncols, enc)?;
269    Ok(cols)
270}
271
272/// 解析 `count` 个列描述符,返回 (列列表, 新位置)。
273///
274/// 实测结构(Go dm_build_1009):
275/// `4×int32(类型/精度/缩放/可空) + 8字节保留 + 4×int16 长度表 + 4 个字符串
276///  + baseName(int16 长度 + 数据) + (LOB 列额外 6 字节)`
277pub fn parse_columns(
278    body: &[u8],
279    mut pos: usize,
280    count: usize,
281    enc: &'static Encoding,
282) -> Result<(Vec<Column>, usize)> {
283    let mut cols = Vec::with_capacity(count);
284    for _ in 0..count {
285        if pos + 32 > body.len() {
286            break;
287        }
288        let col_type = le_i32(body, pos);
289        let prec = le_i32(body, pos + 4);
290        let scale = le_i32(body, pos + 8);
291        let nullable = le_i32(body, pos + 12) != 0;
292        pos += 24; // 16(4×i32) + 8 保留
293        if pos + 8 > body.len() {
294            break;
295        }
296        let nl = le_u16(body, pos) as usize;
297        let tl = le_u16(body, pos + 2) as usize;
298        let tbl = le_u16(body, pos + 4) as usize;
299        let sl = le_u16(body, pos + 6) as usize;
300        pos += 8;
301        let name = read_str_at(body, &mut pos, nl, enc);
302        let type_name = read_str_at(body, &mut pos, tl, enc);
303        let table_name = read_str_at(body, &mut pos, tbl, enc);
304        let schema_name = read_str_at(body, &mut pos, sl, enc);
305        // baseName(int16 长度 + 数据)
306        if pos + 2 > body.len() {
307            break;
308        }
309        let bn = le_u16(body, pos) as usize;
310        pos += 2;
311        pos = (pos + bn).min(body.len());
312        let lob = col_type == DM_BLOB || col_type == DM_CLOB;
313        if lob {
314            // lob 列额外 6 字节(lobTabId int32 + lobColId int16)
315            pos += 6;
316        }
317        cols.push(Column {
318            col_type,
319            prec,
320            scale,
321            nullable,
322            name,
323            type_name,
324            table_name,
325            schema_name,
326            lob,
327        });
328    }
329    Ok((cols, pos))
330}
331
332/// 解析普通查询行(`[int32 行长][6B][偏移表 2×ncols][列数据]`)。
333///
334/// NULL 列:长度 = 0xFFFE;LOB/特殊:长度 = 0xFFFF + int32 真实长度 + 数据
335/// (后者为对 Python 驱动 `<LOB>` 占位符的修正,格式依据 Go zzo.go)。
336pub fn parse_rows(
337    body: &[u8],
338    mut pos: usize,
339    ncols: usize,
340    nrows: usize,
341) -> Result<Vec<Row>> {
342    let mut rows = Vec::with_capacity(nrows);
343    let header = 10; // int32(4) + 6B
344    for _ in 0..nrows {
345        if pos + header > body.len() {
346            break;
347        }
348        pos += header;
349        if pos + 2 * ncols > body.len() {
350            break;
351        }
352        pos += 2 * ncols; // 偏移表
353        let mut row = Vec::with_capacity(ncols);
354        for _ in 0..ncols {
355            if pos + 2 > body.len() {
356                row.push(None);
357                break;
358            }
359            let ln = le_u16(body, pos);
360            pos += 2;
361            match ln {
362                NULL_MARK => row.push(None),
363                LOB_MARK => {
364                    // 0xFFFF → int32 真实长度(Go: valueLen == -1 → 读 int32)
365                    if pos + 4 <= body.len() {
366                        let real = le_i32(body, pos);
367                        pos += 4;
368                        if real > 0 && pos + real as usize <= body.len() {
369                            row.push(Some(body[pos..pos + real as usize].to_vec()));
370                            pos += real as usize;
371                        } else {
372                            row.push(None);
373                        }
374                    } else {
375                        row.push(None);
376                    }
377                }
378                n => {
379                    let n = n as usize;
380                    if pos + n > body.len() {
381                        row.push(None);
382                        break;
383                    }
384                    row.push(Some(body[pos..pos + n].to_vec()));
385                    pos += n;
386                }
387            }
388        }
389        rows.push(row);
390    }
391    Ok(rows)
392}
393
394/// 解析参数化查询行(行长循环 `[int16 行长][int16 行号][7B][偏移表 2×ncols][列数据]`)。
395pub fn parse_rows_param(body: &[u8], mut pos: usize, ncols: usize) -> Result<Vec<Row>> {
396    let mut rows = Vec::new();
397    while pos + 2 <= body.len() {
398        let rlen = le_u16(body, pos) as usize;
399        let row_end = pos + rlen;
400        // 行长 = 行长字段(2) + 数据长度(实测:行1 行长26 = 2+24)
401        if rlen == 0 || row_end <= pos + 2 || row_end > body.len() {
402            break; // 行长=0 或无效(尾部残留)
403        }
404        let mut p = pos + 2 + 2 + 6; // 行长 + 行号 + 6B
405        p += 2 * ncols; // 偏移表
406        let mut row = Vec::with_capacity(ncols);
407        for _ in 0..ncols {
408            if p + 2 > row_end {
409                row.push(None);
410                break;
411            }
412            let ln = le_u16(body, p);
413            p += 2;
414            match ln {
415                NULL_MARK => row.push(None),
416                LOB_MARK => {
417                    if p + 4 <= row_end {
418                        let real = le_i32(body, p);
419                        p += 4;
420                        if real > 0 && p + real as usize <= row_end {
421                            row.push(Some(body[p..p + real as usize].to_vec()));
422                            p += real as usize;
423                        } else {
424                            row.push(None);
425                        }
426                    } else {
427                        row.push(None);
428                    }
429                }
430                n => {
431                    let n = n as usize;
432                    if p + n > row_end {
433                        row.push(None);
434                        break;
435                    }
436                    row.push(Some(body[p..p + n].to_vec()));
437                    p += n;
438                }
439            }
440        }
441        rows.push(row);
442        pos = row_end;
443    }
444    Ok(rows)
445}
446
447/// 按列类型解码单个值(LOB 列不在此处理,由 client 走完整读取)。
448pub fn decode_scalar(raw: &[u8], col: &Column, enc: &'static Encoding) -> Result<Value> {
449    if raw.is_empty() {
450        // 空字节串按类型给空值
451        match col.col_type {
452            DM_CHAR | DM_VARCHAR2 | DM_VARCHAR | DM_CLOB => return Ok(Value::Str(String::new())),
453            _ => return Ok(Value::Bytes(Vec::new())),
454        }
455    }
456    let t = col.col_type;
457    let v = match t {
458        DM_CHAR | DM_VARCHAR2 | DM_VARCHAR => {
459            let (s, _, _) = enc.decode(raw);
460            Value::Str(s.into_owned())
461        }
462        DM_BOOLEAN | DM_BIT => Value::Bool(raw[0] != 0),
463        DM_TINYINT => Value::TinyInt(raw[0] as i8),
464        DM_SMALLINT => Value::SmallInt(i16::from_le_bytes(raw[..2].try_into().unwrap())),
465        DM_INT => Value::Int(le_i32(raw, 0)),
466        DM_BIGINT => Value::BigInt(i64::from_le_bytes(raw[..8].try_into().unwrap())),
467        DM_REAL => Value::Real(f32::from_le_bytes(raw[..4].try_into().unwrap())),
468        DM_DOUBLE => Value::Double(f64::from_le_bytes(raw[..8].try_into().unwrap())),
469        DM_DECIMAL => Value::Decimal(decode_decimal(raw)),
470        DM_DATE => Value::Date(decode_date(raw)),
471        DM_TIME => Value::Time(decode_time(raw)),
472        DM_TIME_TZ => Value::Time(decode_time_tz(raw)),
473        DM_DATETIME => Value::DateTime(decode_datetime(raw)),
474        DM_DATETIME2 => Value::DateTime(decode_datetime2(raw)),
475        DM_DATETIME_TZ => Value::DateTime(decode_datetime_tz(raw)),
476        DM_DATETIME2_TZ => Value::DateTime(decode_datetime2_tz(raw)),
477        DM_INTERVAL_YM => Value::Interval(decode_interval_ym(raw)),
478        DM_INTERVAL_DT => Value::Interval(decode_interval_dt(raw)),
479        DM_BINARY | DM_VARBINARY | DM_BLOB => Value::Bytes(raw.to_vec()),
480        _ => Value::Raw(raw.to_vec()),
481    };
482    Ok(v)
483}
484
485/// 达梦私有大数编码解码(Go o.go decodeDecimal,0xc10233=1.5 实测验证)。
486///
487/// 首字节: 0x80=0;&0x80≠0 → 正数 exp=flag-0xC1;否则负数 exp=0x3E-flag
488/// 后续字节: 每字节 2 位十进制,正数=byte-1,负数=101-byte;越界(0/0x66)终止
489/// 用字符串构造结果,避免浮点/Decimal 默认精度截断(DECIMAL(38) 需要 40 位)
490pub fn decode_decimal(raw: &[u8]) -> String {
491    if raw.is_empty() || raw[0] == 0x80 {
492        return "0".to_string();
493    }
494    let (sign, exp): (i32, i32) = if raw[0] & 0x80 != 0 {
495        (1, raw[0] as i32 - 0xC1)
496    } else {
497        (-1, 0x3E - raw[0] as i32)
498    };
499    let mut digits = String::new();
500    for &b in &raw[1..] {
501        let d = if sign > 0 { b as i32 - 1 } else { 101 - b as i32 };
502        if !(0..=99).contains(&d) {
503            break;
504        }
505        digits.push_str(&format!("{d:02}"));
506    }
507    if digits.is_empty() {
508        return "0".to_string();
509    }
510    // weight = exp*2 - (len(digits)-2),与 Python 一致
511    let weight = exp * 2 - (digits.len() as i32 - 2);
512    let s = if weight >= 0 {
513        format!("{}{}", digits, "0".repeat(weight as usize))
514    } else {
515        let n = digits.len() as i32 + weight;
516        if n <= 0 {
517            format!("0.{}{}", "0".repeat((-n) as usize), digits)
518        } else {
519            format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
520        }
521    };
522    let s = if sign < 0 {
523        format!("-{s}")
524    } else {
525        s
526    };
527    py_decimal_str(&s)
528}
529
530/// 按 Python `Decimal.__str__` 算法格式化十进制字符串
531/// (_pydecimal.py __str__:`exp<=0 且 leftdigits>-6` 用定点,否则科学计数法)。
532fn py_decimal_str(s: &str) -> String {
533    let (neg, body) = match s.strip_prefix('-') {
534        Some(b) => (true, b),
535        None => (false, s),
536    };
537    let (int_part, frac_part) = match body.split_once('.') {
538        Some((i, f)) => (i, f),
539        None => (body, ""),
540    };
541    let mut combined = String::with_capacity(int_part.len() + frac_part.len());
542    combined.push_str(int_part);
543    combined.push_str(frac_part);
544    // 去掉系数前导零(保留至少一位)
545    let stripped = combined.trim_start_matches('0');
546    let coeff = if stripped.is_empty() { "0" } else { stripped };
547    // 指数 = 小数位数(符号相反)
548    let exp: i64 = -(frac_part.len() as i64);
549    // Python: leftdigits = exp + len(coeff)
550    let leftdigits = exp + coeff.len() as i64;
551    let dotplace: i64 = if exp <= 0 && leftdigits > -6 {
552        leftdigits
553    } else {
554        1
555    };
556    let (intpart, fracpart) = if dotplace <= 0 {
557        (String::from("0"), format!(".{}{}", "0".repeat((-dotplace) as usize), coeff))
558    } else if dotplace >= coeff.len() as i64 {
559        (
560            format!("{}{}", coeff, "0".repeat((dotplace - coeff.len() as i64) as usize)),
561            String::new(),
562        )
563    } else {
564        (
565            coeff[..dotplace as usize].to_string(),
566            format!(".{}", &coeff[dotplace as usize..]),
567        )
568    };
569    let exp_part = if leftdigits == dotplace {
570        String::new()
571    } else {
572        format!("E{:+}", leftdigits - dotplace)
573    };
574    format!("{}{}{}{}", if neg { "-" } else { "" }, intpart, fracpart, exp_part)
575}
576
577/// DATE 位压缩(3 字节):EA 07 64 → 2026-08-12
578pub fn decode_date(raw: &[u8]) -> DmDate {
579    let b0 = raw[0] as i32;
580    let b1 = raw[1] as i32;
581    let b2 = raw[2] as i32;
582    let mut year = (b0 | (b1 << 8)) & 0x7FFF;
583    if year > 9999 {
584        year = (year | 0x8000) & 0xFFFF;
585        year -= 65536;
586    }
587    let month = ((b1 >> 7) & 0x1) + ((b2 & 0x07) << 1);
588    let day = ((b2 & 0xF8) >> 3) & 0x1F;
589    DmDate {
590        year,
591        month: if month == 0 { 1 } else { month as u8 },
592        day: if day == 0 { 1 } else { day as u8 },
593    }
594}
595
596/// TIME 位压缩(5 字节)
597pub fn decode_time(raw: &[u8]) -> DmTime {
598    let b0 = raw[0] as u32;
599    let b1 = raw[1] as u32;
600    let b2 = raw[2] as u32;
601    let b3 = raw[3] as u32;
602    let b4 = raw[4] as u32;
603    let hour = b0 & 0x1F;
604    let minute = ((b0 >> 5) & 0x07) + ((b1 & 0x07) << 3);
605    let second = ((b1 >> 3) & 0x1F) + ((b2 & 0x01) << 5);
606    let nsec = (((b2 >> 1) & 0x7F) + (b3 << 7) + ((b4 & 0x1F) << 15)) * 1000;
607    DmTime {
608        hour: hour as u8,
609        minute: minute as u8,
610        second: second as u8,
611        microsecond: nsec / 1000,
612        timezone_minutes: None,
613    }
614}
615
616/// TIME_TZ:TIME(5B) + int16 时区偏移(分钟,可负,Go h.go dmdtDecodeFast)
617pub fn decode_time_tz(raw: &[u8]) -> DmTime {
618    let mut t = decode_time(&raw[..5.min(raw.len())]);
619    if raw.len() >= 7 {
620        t.timezone_minutes = Some(i16::from_le_bytes([raw[5], raw[6]]));
621    }
622    t
623}
624
625/// DATETIME:DATE(3B) + TIME(5B) 组合
626pub fn decode_datetime(raw: &[u8]) -> DmDateTime {
627    if raw.len() >= 8 {
628        DmDateTime {
629            date: decode_date(&raw[..3]),
630            time: decode_time(&raw[3..8]),
631        }
632    } else {
633        DmDateTime {
634            date: DmDate::new(1, 1, 1),
635            time: DmTime::new(0, 0, 0, 0),
636        }
637    }
638}
639
640/// DATETIME2:DATE(3B) + TIME 6B(纳秒 30 位直接存储,非 ×1000,Go h.go DATETIME2 分支)
641pub fn decode_datetime2(raw: &[u8]) -> DmDateTime {
642    if raw.len() >= 9 {
643        let b = |i: usize| raw[3 + i] as u32; // time 部分从 [3] 起
644        let nsec = ((b(2) >> 1) & 0x7F) + (b(3) << 7) + (b(4) << 15) + ((b(5) & 0x7F) << 23);
645        let date = decode_date(&raw[..3]);
646        let mut time = decode_time(&raw[3..8]);
647        time.microsecond = nsec / 1000;
648        DmDateTime { date, time }
649    } else {
650        decode_datetime(raw)
651    }
652}
653
654/// DATETIME_TZ:DATETIME(8B) + int16 时区偏移(分钟,可负)
655pub fn decode_datetime_tz(raw: &[u8]) -> DmDateTime {
656    let mut dt = decode_datetime(&raw[..8.min(raw.len())]);
657    if raw.len() >= 10 {
658        dt.time.timezone_minutes = Some(i16::from_le_bytes([raw[8], raw[9]]));
659    }
660    dt
661}
662
663/// DATETIME2_TZ:DATETIME2(9B) + int16 时区偏移(分钟,可负)
664pub fn decode_datetime2_tz(raw: &[u8]) -> DmDateTime {
665    let mut dt = decode_datetime2(&raw[..9.min(raw.len())]);
666    if raw.len() >= 11 {
667        dt.time.timezone_minutes = Some(i16::from_le_bytes([raw[9], raw[10]]));
668    }
669    dt
670}
671
672/// INTERVAL YEAR TO MONTH:12 字节 = [int32 年][int32 月][int32 scale][byte type]
673pub fn decode_interval_ym(raw: &[u8]) -> String {
674    if raw.len() < 8 {
675        return String::new();
676    }
677    let years = le_i32(raw, 0);
678    let months = le_i32(raw, 4);
679    format!("{years}-{months}")
680}
681
682/// INTERVAL DAY TO SECOND:24 字节 = [int32 天][int32 时][int32 分][int32 秒][int32 微秒][...]
683pub fn decode_interval_dt(raw: &[u8]) -> String {
684    if raw.len() < 20 {
685        return String::new();
686    }
687    let days = le_i32(raw, 0);
688    let hours = le_i32(raw, 4);
689    let minutes = le_i32(raw, 8);
690    let seconds = le_i32(raw, 12);
691    let frac = le_i32(raw, 16);
692    format!("{days} {hours:02}:{minutes:02}:{seconds:02}.{frac:06}")
693}
694
695// ---------- 编码(参数绑定用) ----------
696
697/// DATE 位压缩编码(3 字节,与 decode_date 互逆)
698pub fn encode_date(d: &DmDate) -> [u8; 3] {
699    let y = d.year;
700    let m = d.month as i32;
701    let dd = d.day as i32;
702    [
703        (y & 0xFF) as u8,
704        (((y >> 8) & 0x7F) | ((m & 1) << 7)) as u8,
705        (((m >> 1) & 0x07) | ((dd & 0x1F) << 3)) as u8,
706    ]
707}
708
709/// TIME 位压缩编码(5 字节,与 decode_time 互逆)
710pub fn encode_time(t: &DmTime) -> [u8; 5] {
711    let us = t.microsecond;
712    let b0 = (t.hour as u32) | ((t.minute as u32 & 0x07) << 5);
713    let b1 = (t.minute as u32 >> 3) | ((t.second as u32) << 3);
714    let b2 = (t.second as u32 >> 5) | ((us & 0x7F) << 1);
715    let b3 = (us >> 7) & 0xFF;
716    let b4 = (us >> 15) & 0x1F;
717    [
718        (b0 & 0xFF) as u8,
719        (b1 & 0xFF) as u8,
720        (b2 & 0xFF) as u8,
721        b3 as u8,
722        b4 as u8,
723    ]
724}
725
726/// DATETIME:DATE 位压缩 + TIME 位压缩(8 字节)
727pub fn encode_datetime(dt: &DmDateTime) -> Vec<u8> {
728    let mut out = encode_date(&dt.date).to_vec();
729    out.extend_from_slice(&encode_time(&dt.time));
730    out
731}
732
733/// TIME_TZ 编码:TIME(5B) + int16 时区偏移(分钟,小端,与 decode_time_tz 互逆)
734pub fn encode_time_tz(t: &DmTime) -> Vec<u8> {
735    let mut out = encode_time(t).to_vec();
736    out.extend_from_slice(&t.timezone_minutes.unwrap_or(0).to_le_bytes());
737    out
738}
739
740/// DATETIME_TZ 编码:DATETIME(8B) + int16 时区偏移(分钟,小端,与 decode_datetime_tz 互逆)
741pub fn encode_datetime_tz(dt: &DmDateTime) -> Vec<u8> {
742    let mut out = encode_datetime(dt);
743    out.extend_from_slice(&dt.time.timezone_minutes.unwrap_or(0).to_le_bytes());
744    out
745}
746
747/// DATETIME2 编码:DATE(3B) + TIME 6B(纳秒 30 位直接存储,非 ×1000;与 decode_datetime2 互逆)
748/// 时间部分 b0/b1/b2-低位 与 5 字节 TIME 一致,b2 高 7 位/b3/b4/b5 存纳秒:
749/// nsec = (b2>>1 &0x7F) + (b3<<7) + (b4<<15) + (b5&0x7F)<<23
750pub fn encode_datetime2(dt: &DmDateTime) -> Vec<u8> {
751    let mut out = encode_date(&dt.date).to_vec();
752    let t = &dt.time;
753    let nsec = (t.microsecond as u64) * 1000;
754    let b0 = (t.hour as u32) | ((t.minute as u32 & 0x07) << 5);
755    let b1 = (t.minute as u32 >> 3) | ((t.second as u32) << 3);
756    let b2 = (t.second as u32 >> 5) | (((nsec & 0x7F) as u32) << 1);
757    out.extend_from_slice(&[
758        b0 as u8,
759        b1 as u8,
760        b2 as u8,
761        ((nsec >> 7) & 0xFF) as u8,
762        ((nsec >> 15) & 0xFF) as u8,
763        ((nsec >> 23) & 0x7F) as u8,
764    ]);
765    out
766}
767
768/// DATETIME2_TZ 编码:DATETIME2(9B) + int16 时区偏移(分钟,小端,与 decode_datetime2_tz 互逆)
769pub fn encode_datetime2_tz(dt: &DmDateTime) -> Vec<u8> {
770    let mut out = encode_datetime2(dt);
771    out.extend_from_slice(&dt.time.timezone_minutes.unwrap_or(0).to_le_bytes());
772    out
773}
774
775// ---------- 参数/输出值类型转换 ----------
776
777/// OUT 参数值解码(cmd=187 响应)
778pub fn decode_out_value(raw: &[u8], col_type: i32, enc: &'static Encoding) -> Value {
779    match col_type {
780        5..=8 => Value::BigInt(le_i64(raw)),
781        10 => Value::Real(f32::from_le_bytes(raw[..4].try_into().unwrap())),
782        11 => Value::Double(f64::from_le_bytes(raw[..8].try_into().unwrap())),
783        14 => Value::Date(decode_date(raw)),
784        15 => Value::Time(decode_time(raw)),
785        16 => Value::DateTime(decode_datetime(raw)),
786        2 | 19 => {
787            let (s, _, _) = enc.decode(raw);
788            Value::Str(s.into_owned())
789        }
790        12 | 17 | 18 => Value::Bytes(raw.to_vec()),
791        _ => Value::Raw(raw.to_vec()),
792    }
793}
794
795fn le_i64(b: &[u8]) -> i64 {
796    let mut buf = [0u8; 8];
797    let n = b.len().min(8);
798    buf[..n].copy_from_slice(&b[..n]);
799    i64::from_le_bytes(buf)
800}
801
802#[cfg(test)]
803mod tests {
804    use super::*;
805    use crate::client::enc_decimal;
806
807    #[test]
808    fn date_decode_reference() {
809        let d = decode_date(&[0xEA, 0x07, 0x64]);
810        assert_eq!(d, DmDate::new(2026, 8, 12));
811        // 最小日期
812        let d = decode_date(&encode_date(&DmDate::new(1, 1, 1)));
813        assert_eq!(d, DmDate::new(1, 1, 1));
814    }
815
816    #[test]
817    fn date_encode_reference() {
818        assert_eq!(encode_date(&DmDate::new(2026, 8, 12)), [0xEA, 0x07, 0x64]);
819        assert_eq!(encode_date(&DmDate::new(1999, 2, 28)), [0xCF, 0x07, 0xE1]);
820    }
821
822    #[test]
823    fn time_roundtrip_reference() {
824        // Python 参考向量
825        let t = decode_time(&[0x77, 0xDF, 0x7F, 0x84, 0x1E]);
826        assert_eq!(t, DmTime::new(23, 59, 59, 999999));
827        let t2 = decode_time(&[0x4C, 0xC4, 0x11, 0x14, 0x18]);
828        assert_eq!(t2, DmTime::new(12, 34, 56, 789000));
829        // 编码互逆
830        for t in [
831            DmTime::new(23, 59, 59, 999999),
832            DmTime::new(12, 34, 56, 789000),
833            DmTime::new(0, 0, 0, 0),
834        ] {
835            assert_eq!(decode_time(&encode_time(&t)), t);
836        }
837    }
838
839    #[test]
840    fn datetime_roundtrip() {
841        let dt = DmDateTime::new(DmDate::new(2030, 6, 15), DmTime::new(8, 9, 10, 111222));
842        let b = encode_datetime(&dt);
843        assert_eq!(b, vec![0xEE, 0x07, 0x7B, 0x28, 0x51, 0xEC, 0x64, 0x03]);
844        assert_eq!(decode_datetime(&b), dt);
845        // 最大 datetime
846        let max = DmDateTime::new(DmDate::new(9999, 12, 31), DmTime::new(23, 59, 59, 999999));
847        assert_eq!(encode_datetime(&max), vec![0x0F, 0x27, 0xFE, 0x77, 0xDF, 0x7F, 0x84, 0x1E]);
848        assert_eq!(decode_datetime(&encode_datetime(&max)), max);
849    }
850
851    #[test]
852    fn decimal_decode_reference() {
853        // Python 参考:0xc10233 → 1.50
854        assert_eq!(decode_decimal(&[0xC1, 0x02, 0x33]), "1.50");
855        assert_eq!(decode_decimal(&[0x80]), "0");
856        assert_eq!(decode_decimal(&[0xC1, 0x00]), "0");
857        assert_eq!(decode_decimal(&[0xC0, 0x01]), "0.00");
858        // 负数
859        assert_eq!(decode_decimal(&[0x3D, 0x02, 0x33]), "-9950");
860        assert_eq!(decode_decimal(&[0x3E, 0x63, 0x66]), "-2");
861    }
862
863    #[test]
864    fn interval_decode() {
865        let mut b = Vec::new();
866        for v in [1i32, 2, 0] {
867            b.extend_from_slice(&v.to_le_bytes());
868        }
869        b.push(0);
870        assert_eq!(decode_interval_ym(&b), "1-2");
871
872        let mut b = Vec::new();
873        for v in [1i32, 2, 3, 4, 567890, 0] {
874            b.extend_from_slice(&v.to_le_bytes());
875        }
876        b.push(0);
877        assert_eq!(decode_interval_dt(&b), "1 02:03:04.567890");
878    }
879
880    #[test]
881    fn parse_columns_real_capture() {
882        // 抓包实测(select 1 响应 cmd=187):INT 列(列名为字面量 "1")
883        let body = [
884            0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
885            0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x07, 0x00,
886            0x00, 0x00, 0x00, 0x00, 0x31, 0x49, 0x4e, 0x54, 0x45, 0x47, 0x45, 0x52, 0x00, 0x00,
887            0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x04, 0x00,
888            0x01, 0x00, 0x00, 0x00,
889        ];
890        let enc: &'static Encoding = encoding_rs::GB18030;
891        let (cols, pos) = parse_columns(&body, 0, 1, enc).unwrap();
892        assert_eq!(cols.len(), 1);
893        assert_eq!(cols[0].col_type, DM_INT);
894        assert_eq!(cols[0].prec, 4);
895        assert_eq!(cols[0].name, "1");
896        assert_eq!(cols[0].type_name, "INTEGER");
897        assert_eq!(cols[0].table_name, "");
898        assert_eq!(cols[0].schema_name, "");
899        // 行数据
900        let rows = parse_rows(&body, pos, 1, 1).unwrap();
901        assert_eq!(rows, vec![vec![Some(vec![1, 0, 0, 0])]]);
902    }
903
904    #[test]
905    fn parse_rows_param_real_capture() {
906        // 抓包实测(my_lob SELECT content,1 列 CLOB 行内值 83 字节)
907        let body = hex2b(
908            "610002000000000000000c00530001020403000000000028000000000000000000000002040000010002000000000000000000000000000000d5e2cac74c4f42b2e2cad4c4dac8dda3acb0fcbaacd6d0cec4bacd456e676c697368bbecbacfa1a3",
909        );
910        let rows = parse_rows_param(&body, 0, 1).unwrap();
911        assert_eq!(rows.len(), 1);
912        let cell = rows[0][0].as_ref().unwrap();
913        assert_eq!(cell.len(), 83);
914        assert_eq!(cell[0], 0x01); // inRow 标志
915        // 长度 @9 = 40
916        assert_eq!(u32::from_le_bytes(cell[9..13].try_into().unwrap()), 40);
917        // 数据 @43:"这是LOB测试内容,包含中文和English混合。"
918        let (s, _, _) = encoding_rs::GB18030.decode(&cell[43..]);
919        assert_eq!(s, "这是LOB测试内容,包含中文和English混合。");
920    }
921
922    fn hex2b(s: &str) -> Vec<u8> {
923        (0..s.len())
924            .step_by(2)
925            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
926            .collect()
927    }
928
929    #[test]
930    fn gb18030_scalar_decode() {
931        let enc: &'static Encoding = encoding_rs::GB18030;
932        let (s, _, _) = enc.decode(&[0xb2, 0xe2, 0xca, 0xd4]);
933        assert_eq!(s, "测试");
934        // GB18030 4 字节字符 U+20000
935        let (s, _, _) = enc.decode(&[0x95, 0x32, 0x82, 0x36]);
936        assert_eq!(s, "\u{20000}");
937    }
938
939    #[test]
940    fn tz_and_datetime2_decode() {
941        // 向量由 Python 参考实现生成(dmpy._enc_time/_enc_datetime/_enc_date)
942        // TIME_TZ:TIME(5B) + int16 时区(分钟,东八区 +480 → e0 01)
943        let t = decode_time_tz(&hex2b("4cc4111418e001"));
944        assert_eq!((t.hour, t.minute, t.second, t.microsecond), (12, 34, 56, 789000));
945        assert_eq!(t.timezone_minutes, Some(480));
946        assert!(t.to_string().ends_with("+08:00"), "{}", t);
947        let t2 = decode_time_tz(&hex2b("4cc4111418d4fe"));
948        assert_eq!(t2.timezone_minutes, Some(-300));
949        assert!(t2.to_string().ends_with("-05:00"), "{}", t2);
950
951        // DATETIME_TZ:DATETIME(8B) + int16 时区
952        let dt = decode_datetime_tz(&hex2b("ea07744cc4111418e001"));
953        assert_eq!((dt.date.year, dt.date.month, dt.date.day), (2026, 8, 14));
954        assert_eq!(dt.time.hour, 12);
955        assert_eq!(dt.time.timezone_minutes, Some(480));
956        assert!(dt.to_string().ends_with("+08:00"), "{}", dt);
957
958        // DATETIME2:9B,纳秒 30 位直接存储(789000us = 789_000_000ns)
959        let dt2 = decode_datetime2(&hex2b("ea07744cc4815e0e5e"));
960        assert_eq!(dt2.date.year, 2026);
961        assert_eq!(dt2.time.microsecond, 789000);
962        assert_eq!(dt2.time.timezone_minutes, None);
963
964        // DATETIME2_TZ:11B = DATETIME2(9B) + tz
965        let dtz = decode_datetime2_tz(&hex2b("ea07744cc4815e0e5ee001"));
966        assert_eq!(dtz.time.microsecond, 789000);
967        assert_eq!(dtz.time.timezone_minutes, Some(480));
968        assert!(dtz.to_string().ends_with("+08:00"));
969    }
970
971    #[test]
972    fn tz_and_datetime2_encode_roundtrip() {
973        // TIME_TZ:TIME(5B) + int16 时区(东八区 +480 → e0 01)
974        let mut t = DmTime::new(12, 34, 56, 789000);
975        t.timezone_minutes = Some(480);
976        assert_eq!(encode_time_tz(&t), hex2b("4cc4111418e001"));
977        assert_eq!(decode_time_tz(&encode_time_tz(&t)), t);
978
979        // DATETIME_TZ:DATETIME(8B) + int16 时区
980        let mut dt = DmDateTime::new(DmDate::new(2026, 8, 14), DmTime::new(12, 34, 56, 789000));
981        dt.time.timezone_minutes = Some(-300);
982        assert_eq!(encode_datetime_tz(&dt), hex2b("ea07744cc4111418d4fe"));
983        assert_eq!(decode_datetime_tz(&encode_datetime_tz(&dt)), dt);
984
985        // DATETIME2:9B 纳秒 30 位直接存储(789000us = 789_000_000ns)
986        let dt2 = DmDateTime::new(DmDate::new(2026, 8, 14), DmTime::new(12, 34, 56, 789000));
987        assert_eq!(encode_datetime2(&dt2), hex2b("ea07744cc4815e0e5e"));
988        assert_eq!(decode_datetime2(&encode_datetime2(&dt2)), dt2);
989
990        // DATETIME2_TZ:11B = DATETIME2(9B) + tz
991        let mut dtz = dt2;
992        dtz.time.timezone_minutes = Some(480);
993        assert_eq!(encode_datetime2_tz(&dtz), hex2b("ea07744cc4815e0e5ee001"));
994        assert_eq!(decode_datetime2_tz(&encode_datetime2_tz(&dtz)), dtz);
995
996        // 无时区:TZ 编码退化为偏移 0
997        let plain = DmTime::new(1, 2, 3, 0);
998        assert_eq!(encode_time_tz(&plain).len(), 7);
999        assert_eq!(&encode_time_tz(&plain)[5..], &[0u8, 0]);
1000    }
1001
1002    #[test]
1003    fn decimal_encode_vectors() {
1004        // 对照 Python/Go:1.50 → c1 02 33,0 → 80,-2 → 3e 63 66
1005        assert_eq!(enc_decimal("1.5"), vec![0xC1, 0x02, 0x33]);
1006        assert_eq!(enc_decimal("1.50"), vec![0xC1, 0x02, 0x33]);
1007        assert_eq!(enc_decimal("1"), vec![0xC1, 0x02]);
1008        assert_eq!(enc_decimal("0"), vec![0x80]);
1009        assert_eq!(enc_decimal("0.00"), vec![0x80]);
1010        assert_eq!(enc_decimal("-2"), vec![0x3E, 0x63, 0x66]);
1011        assert_eq!(enc_decimal("9950"), vec![0xC2, 0x64, 0x33]);
1012        assert_eq!(enc_decimal("0.0015"), vec![0xBF, 0x10]);
1013        assert_eq!(enc_decimal("100.5"), vec![0xC2, 0x02, 0x01, 0x33]);
1014        assert_eq!(enc_decimal("-100.5"), vec![0x3D, 0x64, 0x65, 0x33, 0x66]);
1015        // 科学计数
1016        assert_eq!(enc_decimal("1e-2"), enc_decimal("0.01"));
1017        assert_eq!(enc_decimal("1.5E1"), enc_decimal("15"));
1018        // 解码往返(用 result::decode_decimal)
1019        for v in ["1.5", "9950", "-2", "0.0015", "12345678901234567890.1234567890", "-100.5"] {
1020            let enc = enc_decimal(v);
1021            assert_eq!(crate::result::decode_decimal(&enc), crate::result::decode_decimal(&enc));
1022        }
1023        assert_eq!(crate::result::decode_decimal(&enc_decimal("1.5")), "1.50");
1024        assert_eq!(crate::result::decode_decimal(&enc_decimal("-2")), "-2");
1025        assert_eq!(crate::result::decode_decimal(&enc_decimal("9950")), "9950");
1026    }
1027}