yang-db 0.3.1

个人使用数据库操作
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::{DbError, RedisClient, RedisValue, Result};
use redis::FromRedisValue;

/// Redis Pipeline 批量操作
///
/// Pipeline 允许将多个命令打包发送到 Redis 服务器,减少网络往返次数,提高性能。
/// 基于 redis-rs 的原生 `redis::pipe()` 实现。
///
/// # 特性
/// - 支持所有 Redis 命令
/// - 按添加顺序返回结果
/// - 单次网络往返执行所有命令
/// - 非原子性(与事务不同)
///
/// # 示例
/// ```no_run
/// use yang_db::RedisClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
///     
///     let mut pipeline = client.pipeline();
///     pipeline.set("key1", "value1");
///     pipeline.set("key2", "value2");
///     pipeline.get("key1");
///     pipeline.incr("counter");
///
///     let results = pipeline.execute().await?;
///     println!("Pipeline 执行结果: {:?}", results);
///     
///     Ok(())
/// }
/// ```
pub struct RedisPipeline {
    /// 原生 redis::Pipeline
    pipe: redis::Pipeline,
    /// Redis 客户端引用
    client: RedisClient,
}

impl RedisPipeline {
    /// 创建新的 Pipeline
    ///
    /// # 参数
    /// - `client`: Redis 客户端
    ///
    /// # 返回
    /// 新的 Pipeline 实例
    ///
    /// # 示例
    /// ```no_run
    /// use yang_db::RedisClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
    ///     let pipeline = client.pipeline();
    ///     Ok(())
    /// }
    /// ```
    pub fn new(client: RedisClient) -> Self {
        Self {
            pipe: redis::pipe(),
            client,
        }
    }

    /// 添加 SET 命令
    ///
    /// # 参数
    /// - `key`: 键
    /// - `value`: 值
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    ///
    /// # 示例
    /// ```no_run
    /// # use yang_db::RedisClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
    /// let mut pipeline = client.pipeline();
    /// pipeline.set("key1", "value1")
    ///         .set("key2", "value2");
    /// # Ok(())
    /// # }
    /// ```
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.pipe.set(key.into(), value.into());
        self
    }

    /// 添加 GET 命令
    ///
    /// # 参数
    /// - `key`: 键
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn get(&mut self, key: impl Into<String>) -> &mut Self {
        self.pipe.get(key.into());
        self
    }

    /// 添加 EXISTS 命令(单键)
    ///
    /// 检查单个键是否存在,结果为 `Int(0)` 或 `Int(1)`。
    ///
    /// # 参数
    /// - `key`: 键
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn exists(&mut self, key: impl Into<String>) -> &mut Self {
        self.pipe.exists(key.into());
        self
    }

    /// 添加 DEL 命令
    ///
    /// # 参数
    /// - `keys`: 要删除的键列表
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn del(&mut self, keys: &[String]) -> &mut Self {
        self.pipe.del(keys);
        self
    }

    /// 添加 INCR 命令
    ///
    /// # 参数
    /// - `key`: 键
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn incr(&mut self, key: impl Into<String>) -> &mut Self {
        self.pipe.incr(key.into(), 1);
        self
    }

    /// 添加 HSET 命令
    ///
    /// # 参数
    /// - `key`: 哈希表键
    /// - `field`: 字段名
    /// - `value`: 字段值
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn hset(
        &mut self,
        key: impl Into<String>,
        field: impl Into<String>,
        value: impl Into<String>,
    ) -> &mut Self {
        self.pipe.hset(key.into(), field.into(), value.into());
        self
    }

    /// 添加 HGET 命令
    ///
    /// # 参数
    /// - `key`: 哈希表键
    /// - `field`: 字段名
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn hget(&mut self, key: impl Into<String>, field: impl Into<String>) -> &mut Self {
        self.pipe.hget(key.into(), field.into());
        self
    }

    /// 添加 LPUSH 命令
    ///
    /// # 参数
    /// - `key`: 列表键
    /// - `values`: 要插入的值列表
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    ///
    /// 多元素打包为**单条** LPUSH 命令(NEW-21),保证「每方法调用一条命令一个结果」
    /// 契约。空切片为 no-op(不下发命令)以避免 redis 报参数错误。
    pub fn lpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self {
        if !values.is_empty() {
            self.pipe.lpush(key.into(), values);
        }
        self
    }

    /// 添加 RPUSH 命令
    ///
    /// # 参数
    /// - `key`: 列表键
    /// - `values`: 要插入的值列表
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn rpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self {
        if !values.is_empty() {
            self.pipe.rpush(key.into(), values);
        }
        self
    }

    /// 添加 SADD 命令
    ///
    /// # 参数
    /// - `key`: 集合键
    /// - `members`: 要添加的成员列表
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn sadd(&mut self, key: impl Into<String>, members: &[String]) -> &mut Self {
        if !members.is_empty() {
            self.pipe.sadd(key.into(), members);
        }
        self
    }

    /// 添加 ZADD 命令
    ///
    /// # 参数
    /// - `key`: 有序集合键
    /// - `members`: (分数, 成员) 元组列表
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    pub fn zadd(&mut self, key: impl Into<String>, members: &[(f64, String)]) -> &mut Self {
        if !members.is_empty() {
            // redis-rs zadd_multiple 接受 &[(score, member)],一次性打包为单条命令
            let pairs: Vec<(f64, &str)> = members.iter().map(|(s, m)| (*s, m.as_str())).collect();
            self.pipe.zadd_multiple(key.into(), &pairs);
        }
        self
    }

    /// 添加自定义命令
    ///
    /// # 参数
    /// - `cmd`: Redis 命令
    ///
    /// # 返回
    /// 返回 self 以支持链式调用
    ///
    /// # 示例
    /// ```no_run
    /// # use yang_db::RedisClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
    /// let mut pipeline = client.pipeline();
    /// let mut cmd = redis::cmd("SETEX");
    /// cmd.arg("key").arg(60).arg("value");
    /// pipeline.cmd(cmd);
    /// # Ok(())
    /// # }
    /// ```
    pub fn cmd(&mut self, cmd: redis::Cmd) -> &mut Self {
        self.pipe.add_command(cmd);
        self
    }

    /// 校验 Pipeline 命令数是否超过配置上限。
    fn ensure_within_limit(&self) -> Result<()> {
        let count = self.pipe.cmd_iter().count();
        let max = self.client.config().pipeline_max_commands;
        if count > max {
            return Err(DbError::InvalidArgument(format!(
                "Pipeline 命令数 {count} 超过上限 {max}"
            )));
        }
        Ok(())
    }

    /// 执行 Pipeline 中的所有命令(类型化版本)
    ///
    /// # 类型参数
    /// - `T`: 实现了 `FromRedisValue` 的类型
    ///
    /// # 返回
    /// - `Ok(Vec<T>)`: 按命令添加顺序返回的结果列表
    /// - `Err(DbError)`: 执行失败
    ///
    /// # 错误处理
    /// 任一命令失败时整体返回一个错误(redis-rs 的限制,不携带命令索引);
    /// 需要逐条结果请使用 [`execute_tolerant`](Self::execute_tolerant)。
    ///
    /// # 示例
    /// ```no_run
    /// # use yang_db::RedisClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
    /// let mut pipeline = client.pipeline();
    /// pipeline.set("key1", "value1")
    ///         .set("key2", "value2")
    ///         .get("key1");
    ///
    /// // 获取类型化结果
    /// let results: Vec<String> = pipeline.query().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "redis", db.operation = "pipeline", otel.kind = "client")
    )]
    pub async fn query<T: FromRedisValue>(self) -> Result<Vec<T>> {
        self.ensure_within_limit()?;
        let mut conn = self.client.connection().await?;
        conn.query_pipeline::<Vec<T>>(&self.pipe)
            .await
            .map_err(DbError::from)
    }

    /// 执行 Pipeline 中的所有命令(兼容模式)
    ///
    /// # 返回
    /// - `Ok(Vec<RedisValue>)`: 按命令添加顺序返回的结果列表
    /// - `Err(DbError)`: 执行失败
    ///
    /// # 错误处理
    /// 如果某个命令失败,返回错误并指明失败的命令索引
    ///
    /// # 示例
    /// ```no_run
    /// # use yang_db::RedisClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
    /// let mut pipeline = client.pipeline();
    /// pipeline.set("key1", "value1")
    ///         .set("key2", "value2")
    ///         .get("key1")
    ///         .incr("counter");
    ///
    /// let results = pipeline.execute().await?;
    /// println!("Pipeline 执行结果: {:?}", results);
    /// # Ok(())
    /// # }
    /// ```
    #[tracing::instrument(
        name = "db.query",
        skip_all,
        fields(db.system = "redis", db.operation = "pipeline", otel.kind = "client")
    )]
    pub async fn execute(self) -> Result<Vec<RedisValue>> {
        self.ensure_within_limit()?;
        let mut conn = self.client.connection().await?;
        let results: Vec<redis::Value> = conn
            .query_pipeline(&self.pipe)
            .await
            .map_err(DbError::from)?;
        Ok(results.into_iter().map(RedisValue::from).collect())
    }

    /// 容错执行:逐条返回每个命令的结果,单条错误不会吞掉其他命令的结果。
    ///
    /// 该方法是「正确性优先」的实现:它不把命令打包为一次网络往返,而是逐条执行,
    /// 因此缺少 Pipeline 的吞吐优势。常规路径请使用 [`execute`](Self::execute)。
    ///
    /// 返回的外层 `Result` 只表示连接/类型级失败;内层 `Result` 表示单条命令结果。
    pub async fn execute_tolerant(self) -> Result<Vec<Result<RedisValue>>> {
        self.ensure_within_limit()?;
        let mut conn = self.client.connection().await?;
        let mut results = Vec::with_capacity(self.pipe.cmd_iter().count());
        for cmd in self.pipe.cmd_iter() {
            let result = conn
                .query::<redis::Value>(cmd)
                .await
                .map(RedisValue::from)
                .map_err(DbError::from);
            results.push(result);
        }
        Ok(results)
    }

    /// 获取 Pipeline 中的命令数量
    ///
    /// # 返回
    /// Pipeline 中的命令数量
    pub fn len(&self) -> usize {
        self.pipe.cmd_iter().count()
    }

    /// 检查 Pipeline 是否为空
    ///
    /// # 返回
    /// - `true`: Pipeline 为空
    /// - `false`: Pipeline 不为空
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_pipeline_creation() {
        // 注意:这里只测试结构体创建,不测试实际连接
        // 实际连接测试在集成测试中进行
    }

    #[test]
    fn test_pipeline_len_empty() {
        // 测试空 Pipeline
        // 注意:需要实际的 RedisClient 才能创建 Pipeline
        // 这个测试只是占位符,实际测试在集成测试中
    }
}