Skip to main content

dm_pure/
cursor.rs

1//! DB-API 风格惰性游标:`fetchone` / `fetchmany` / `fetchall` 按需拉取,大结果集自动分批。
2
3use crate::client::{LazyState, Param};
4use crate::result::{Column, Value};
5use crate::{DmClient, ExecuteResult, Result};
6
7/// DB-API 风格游标。惰性查询(参数化 SELECT)只拉第一帧,fetch 时按需拉取剩余批次。
8pub struct Cursor<'a> {
9    client: &'a mut DmClient,
10    /// 列描述(查询后填充)
11    pub columns: Vec<Column>,
12    /// 行缓存
13    rows: Vec<Vec<Value>>,
14    pos: usize,
15    /// 影响行数(DML)或已拉取行数(查询)
16    pub rowcount: i64,
17    /// fetchmany 默认大小
18    pub arraysize: usize,
19    lazy: Option<LazyState>,
20}
21
22impl<'a> Cursor<'a> {
23    pub fn new(client: &'a mut DmClient) -> Self {
24        Cursor {
25            client,
26            columns: Vec::new(),
27            rows: Vec::new(),
28            pos: 0,
29            rowcount: -1,
30            arraysize: 100,
31            lazy: None,
32        }
33    }
34
35    /// DB-API description:`(name, type_code, display_size, internal_size, precision, scale, null_ok)`
36    #[allow(clippy::type_complexity)]
37    pub fn description(&self) -> Vec<(String, i32, Option<i32>, Option<i32>, i32, i32, Option<bool>)> {
38        self.columns
39            .iter()
40            .map(|c| {
41                (
42                    c.name.clone(),
43                    c.col_type,
44                    None,
45                    None,
46                    c.prec,
47                    c.scale,
48                    if c.nullable { Some(true) } else { Some(false) },
49                )
50            })
51            .collect()
52    }
53
54    /// 执行 SQL。大结果集(参数化查询)使用惰性分批 fetch。
55    pub fn execute(&mut self, sql: &str, params: &[Param]) -> Result<&mut Self> {
56        if is_query(sql) && !params.is_empty() {
57            // 惰性查询(参数化):只拉第一帧,fetchone 时按需拉取
58            let (cols, state) = self.client.execute_lazy(sql, params)?;
59            let stmt = state.stmt;
60            let decoded = self.client.decode_rows(&cols, &state.rows_raw, stmt)?;
61            self.columns = cols;
62            self.lazy = Some(state);
63            self.rows = decoded;
64            self.pos = 0;
65            self.rowcount = self.rows.len() as i64;
66            return Ok(self);
67        }
68        let result = self.client.execute(sql, params)?;
69        self.lazy = None;
70        self.pos = 0;
71        match result {
72            ExecuteResult::Query { columns, rows } => {
73                self.columns = columns;
74                self.rows = rows;
75                self.rowcount = self.rows.len() as i64;
76            }
77            ExecuteResult::Affected(n) => {
78                self.columns = Vec::new();
79                self.rows = Vec::new();
80                self.rowcount = n as i64;
81            }
82            ExecuteResult::Call { affected, .. } => {
83                self.columns = Vec::new();
84                self.rows = Vec::new();
85                self.rowcount = affected as i64;
86            }
87        }
88        Ok(self)
89    }
90
91    /// 批量执行(协议级 batch)。返回总影响行数。
92    pub fn executemany(&mut self, sql: &str, seq_of_params: &[Vec<Param>]) -> Result<u64> {
93        if seq_of_params.is_empty() {
94            return Ok(0);
95        }
96        self.client.executemany(sql, seq_of_params)
97    }
98
99    fn ensure_batch(&mut self) -> Result<()> {
100        let need_more = match &self.lazy {
101            Some(s) => s.more && self.pos >= self.rows.len(),
102            None => false,
103        };
104        if need_more {
105            let stmt = self.lazy.as_ref().unwrap().stmt;
106            let ncols = self.lazy.as_ref().unwrap().ncols;
107            let start = self.lazy.as_ref().unwrap().rows_raw.len() as i64;
108            let more_raw = self.client.fetch_more(stmt, start, ncols)?;
109            let decoded = self.client.decode_rows(&self.columns, &more_raw, stmt)?;
110            let state = self.lazy.as_mut().unwrap();
111            state.rows_raw.extend(more_raw);
112            state.more = false; // cmd=7 一次拉剩余
113            self.rows.extend(decoded);
114        }
115        Ok(())
116    }
117
118    pub fn fetchone(&mut self) -> Result<Option<Vec<Value>>> {
119        self.ensure_batch()?;
120        if self.pos >= self.rows.len() {
121            return Ok(None);
122        }
123        let row = self.rows[self.pos].clone();
124        self.pos += 1;
125        Ok(Some(row))
126    }
127
128    pub fn fetchmany(&mut self, size: Option<usize>) -> Result<Vec<Vec<Value>>> {
129        let size = size.unwrap_or(self.arraysize);
130        // 缓存不足且还有更多时直接拉取
131        loop {
132            let more = match &self.lazy {
133                Some(s) => s.more,
134                None => false,
135            };
136            if !(more && self.pos + size > self.rows.len()) {
137                break;
138            }
139            let stmt = self.lazy.as_ref().unwrap().stmt;
140            let ncols = self.lazy.as_ref().unwrap().ncols;
141            let start = self.lazy.as_ref().unwrap().rows_raw.len() as i64;
142            let more_raw = self.client.fetch_more(stmt, start, ncols)?;
143            if more_raw.is_empty() {
144                break;
145            }
146            let decoded = self.client.decode_rows(&self.columns, &more_raw, stmt)?;
147            let state = self.lazy.as_mut().unwrap();
148            state.rows_raw.extend(more_raw);
149            state.more = false;
150            self.rows.extend(decoded);
151        }
152        let end = (self.pos + size).min(self.rows.len());
153        let rows = self.rows[self.pos..end].to_vec();
154        self.pos = end;
155        Ok(rows)
156    }
157
158    pub fn fetchall(&mut self) -> Result<Vec<Vec<Value>>> {
159        // 直接拉取所有剩余批次(fetch_more 内部循环到取完,一次调用返回全部剩余行),
160        // 不依赖 pos 位置(修复:此前 while more + ensure_batch 在当前批次未消费完时死循环)
161        while match &self.lazy {
162            Some(s) => s.more,
163            None => false,
164        } {
165            let stmt = self.lazy.as_ref().unwrap().stmt;
166            let ncols = self.lazy.as_ref().unwrap().ncols;
167            let start = self.lazy.as_ref().unwrap().rows_raw.len() as i64;
168            let more_raw = self.client.fetch_more(stmt, start, ncols)?;
169            let decoded = self.client.decode_rows(&self.columns, &more_raw, stmt)?;
170            let state = self.lazy.as_mut().unwrap();
171            state.rows_raw.extend(more_raw);
172            state.more = false; // cmd=7 一次拉剩余(内部循环到取完)
173            self.rows.extend(decoded);
174        }
175        let rows = self.rows[self.pos..].to_vec();
176        self.pos = self.rows.len();
177        Ok(rows)
178    }
179
180    /// 释放惰性游标的语句资源(cmd=44 + cmd=4)。
181    pub fn close(&mut self) {
182        if let Some(mut state) = self.lazy.take() {
183            let _ = self.client.close_lazy(&mut state);
184        }
185        self.rows.clear();
186    }
187}
188
189impl<'a> Drop for Cursor<'a> {
190    fn drop(&mut self) {
191        self.close();
192    }
193}
194
195fn is_query(sql: &str) -> bool {
196    crate::client::is_query_sql(sql)
197}