yang-db 0.3.0

个人使用数据库操作
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! 常用命令补遗:SET/ZADD 选项、键管理、Bitmap/HLL/GEO 薄封装。
//!
//! 这些命令都走统一的超时、重连与指标路径;复杂命令仍可通过
//! [`RedisClient::execute`](crate::RedisClient::execute) 逃生口发送。

use crate::redis::client::{collect_string_array, optional_string, parse_with_scores};
use crate::{DbError, RedisClient, Result};

/// SET 选项。
#[derive(Debug, Clone, Copy, Default)]
pub struct SetOptions {
    /// 仅当 key 不存在时设置
    pub nx: bool,
    /// 仅当 key 存在时设置
    pub xx: bool,
    /// 返回旧值(与 NX/XX 组合时语义见 Redis 文档)
    pub get: bool,
    /// 过期时间(秒)
    pub ex_seconds: Option<i64>,
    /// 过期时间(毫秒)
    pub px_millis: Option<i64>,
    /// 保留原 TTL
    pub keepttl: bool,
}

/// SET 条件写的执行结果。
///
/// 由 [`RedisClient::set_with_options_outcome`] 返回,用于区分「写入已生效」
/// 与「因 `NX`/`XX` 条件不满足而未写入」:`SET` 的条件写回复只有 `+OK` 与
/// `nil` 两种,[`RedisClient::set_with_options`] 在 `get=false` 时把两者折叠成
/// `Ok(None)`,调用方无法感知写入是否被跳过。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetOutcome {
    /// 写入已生效。
    Applied,
    /// 因 `NX`/`XX` 条件不满足而未写入。
    NotApplied,
}

/// ZADD 选项。
#[derive(Debug, Clone, Copy, Default)]
pub struct ZAddOptions {
    /// 仅新增
    pub nx: bool,
    /// 仅更新已有成员
    pub xx: bool,
    /// 仅当新分数更高时更新
    pub gt: bool,
    /// 仅当新分数更低时更新
    pub lt: bool,
    /// 返回被修改的成员数(默认返回新增数)
    pub ch: bool,
}

/// GETEX 过期选项。
#[derive(Debug, Clone, Copy)]
pub enum GetExOption {
    /// 秒级过期
    Ex(i64),
    /// 毫秒级过期
    Px(i64),
    /// 移除过期时间
    Persist,
}

impl RedisClient {
    // ==================== String 补遗 ====================

    /// GETDEL:读取并删除。
    pub async fn getdel(&self, key: impl Into<String>) -> Result<Option<String>> {
        let mut cmd = redis::cmd("GETDEL");
        cmd.arg(key.into());
        optional_string(&self.execute(&cmd).await?)
    }

    /// GETEX:读取并更新过期时间。
    pub async fn getex(
        &self,
        key: impl Into<String>,
        option: Option<GetExOption>,
    ) -> Result<Option<String>> {
        let mut cmd = redis::cmd("GETEX");
        cmd.arg(key.into());
        match option {
            Some(GetExOption::Ex(seconds)) => {
                cmd.arg("EX").arg(seconds);
            }
            Some(GetExOption::Px(millis)) => {
                cmd.arg("PX").arg(millis);
            }
            Some(GetExOption::Persist) => {
                cmd.arg("PERSIST");
            }
            None => {}
        }
        optional_string(&self.execute(&cmd).await?)
    }

    /// SET 带选项;`get=true` 时返回旧值。
    ///
    /// # 返回语义
    /// - `get=true`: 返回 key 的旧值(key 不存在时为 `None`)。
    /// - `get=false`: **始终返回 `Ok(None)`**。此时 `SET` 的回复只有 `+OK`
    ///   与 `nil` 两种,`NX`/`XX` 条件是否真正生效无法从返回值区分;需要
    ///   判断条件写结果时请改用
    ///   [`set_with_options_outcome`](Self::set_with_options_outcome)。
    pub async fn set_with_options(
        &self,
        key: impl Into<String>,
        value: impl Into<String>,
        options: SetOptions,
    ) -> Result<Option<String>> {
        if options.nx && options.xx {
            return Err(DbError::InvalidArgument(
                "SET 选项 NX 与 XX 不能同时使用".to_string(),
            ));
        }
        if options.ex_seconds.is_some() && options.px_millis.is_some() {
            return Err(DbError::InvalidArgument(
                "SET 选项 EX 与 PX 不能同时使用".to_string(),
            ));
        }
        if options.keepttl && (options.ex_seconds.is_some() || options.px_millis.is_some()) {
            return Err(DbError::InvalidArgument(
                "SET 选项 KEEPTTL 不能与 EX/PX 同时使用".to_string(),
            ));
        }
        let mut cmd = redis::cmd("SET");
        cmd.arg(key.into()).arg(value.into());
        if options.nx {
            cmd.arg("NX");
        } else if options.xx {
            cmd.arg("XX");
        }
        if options.get {
            cmd.arg("GET");
        }
        if let Some(seconds) = options.ex_seconds {
            cmd.arg("EX").arg(seconds);
        } else if let Some(millis) = options.px_millis {
            cmd.arg("PX").arg(millis);
        } else if options.keepttl {
            cmd.arg("KEEPTTL");
        }
        let result = self.execute(&cmd).await?;
        if options.get {
            optional_string(&result)
        } else {
            Ok(None)
        }
    }

    /// SET 带选项,并报告 `NX`/`XX` 条件写是否真正生效。
    ///
    /// 与 [`set_with_options`](Self::set_with_options) 相比,本方法不返回旧值,
    /// 而是明确区分 [`SetOutcome::Applied`] 与 [`SetOutcome::NotApplied`]:
    ///
    /// - `get=false`: `+OK` 映射为 `Applied`;`nil` 映射为 `NotApplied`
    ///   (只有 `NX`/`XX` 条件不满足时才会出现)。
    /// - `get=true`: Redis 返回旧值(key 不存在时为 `nil`),本方法按
    ///   `NX`/`XX` 语义反推是否生效;旧值本身请用
    ///   [`set_with_options`](Self::set_with_options) 获取。
    ///
    /// 选项合法性校验、命令构造与 [`set_with_options`](Self::set_with_options)
    /// 一致,非法组合返回同样的 [`DbError::InvalidArgument`]。
    pub async fn set_with_options_outcome(
        &self,
        key: impl Into<String>,
        value: impl Into<String>,
        options: SetOptions,
    ) -> Result<SetOutcome> {
        // 有意复制 set_with_options 的校验与命令构造:旧方法的签名、方法体
        // 与 get=false 恒返回 Ok(None) 的契约必须原样保留,不能为复用而改动。
        if options.nx && options.xx {
            return Err(DbError::InvalidArgument(
                "SET 选项 NX 与 XX 不能同时使用".to_string(),
            ));
        }
        if options.ex_seconds.is_some() && options.px_millis.is_some() {
            return Err(DbError::InvalidArgument(
                "SET 选项 EX 与 PX 不能同时使用".to_string(),
            ));
        }
        if options.keepttl && (options.ex_seconds.is_some() || options.px_millis.is_some()) {
            return Err(DbError::InvalidArgument(
                "SET 选项 KEEPTTL 不能与 EX/PX 同时使用".to_string(),
            ));
        }
        let mut cmd = redis::cmd("SET");
        cmd.arg(key.into()).arg(value.into());
        if options.nx {
            cmd.arg("NX");
        } else if options.xx {
            cmd.arg("XX");
        }
        if options.get {
            cmd.arg("GET");
        }
        if let Some(seconds) = options.ex_seconds {
            cmd.arg("EX").arg(seconds);
        } else if let Some(millis) = options.px_millis {
            cmd.arg("PX").arg(millis);
        } else if options.keepttl {
            cmd.arg("KEEPTTL");
        }
        let result = self.execute(&cmd).await?;
        Ok(classify_set_outcome(&result, &options))
    }

    /// MSETNX:仅当所有 key 都不存在时批量设置。
    pub async fn msetnx(&self, pairs: &[(String, String)]) -> Result<bool> {
        if pairs.is_empty() {
            return Ok(true);
        }
        let mut cmd = redis::cmd("MSETNX");
        for (key, value) in pairs {
            cmd.arg(key).arg(value);
        }
        Ok(self.execute(&cmd).await?.as_i64() == Some(1))
    }

    // ==================== Hash 补遗 ====================

    /// HSETNX:字段不存在时设置。
    pub async fn hsetnx(
        &self,
        key: impl Into<String>,
        field: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<bool> {
        let mut cmd = redis::cmd("HSETNX");
        cmd.arg(key.into()).arg(field.into()).arg(value.into());
        Ok(self.execute(&cmd).await?.as_i64() == Some(1))
    }

    /// HSET 多字段版本,返回新增字段数。
    pub async fn hset_multiple(
        &self,
        key: impl Into<String>,
        fields: &[(String, String)],
    ) -> Result<i64> {
        if fields.is_empty() {
            return Ok(0);
        }
        let mut cmd = redis::cmd("HSET");
        cmd.arg(key.into());
        for (field, value) in fields {
            cmd.arg(field).arg(value);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// HRANDFIELD:随机返回一个字段。
    pub async fn hrandfield(&self, key: impl Into<String>) -> Result<Option<String>> {
        let mut cmd = redis::cmd("HRANDFIELD");
        cmd.arg(key.into());
        optional_string(&self.execute(&cmd).await?)
    }

    /// HRANDFIELD COUNT:随机返回多个字段。
    pub async fn hrandfield_count(
        &self,
        key: impl Into<String>,
        count: i64,
    ) -> Result<Vec<String>> {
        let mut cmd = redis::cmd("HRANDFIELD");
        cmd.arg(key.into()).arg(count);
        collect_string_array(&self.execute(&cmd).await?)
    }

    /// HRANDFIELD COUNT WITHVALUES:随机返回字段与值。
    pub async fn hrandfield_with_values(
        &self,
        key: impl Into<String>,
        count: i64,
    ) -> Result<Vec<(String, String)>> {
        let mut cmd = redis::cmd("HRANDFIELD");
        cmd.arg(key.into()).arg(count).arg("WITHVALUES");
        let flat = collect_string_array(&self.execute(&cmd).await?)?;
        if flat.len() % 2 != 0 {
            return Err(DbError::RedisTypeConversionError(
                "HRANDFIELD WITHVALUES 返回数量不是偶数".to_string(),
            ));
        }
        Ok(flat
            .chunks_exact(2)
            .map(|pair| (pair[0].clone(), pair[1].clone()))
            .collect())
    }

    // ==================== List 补遗 ====================

    /// LMOVE:从源列表一端弹出并推入目标列表一端。
    pub async fn lmove(
        &self,
        source: impl Into<String>,
        destination: impl Into<String>,
        from_left: bool,
        to_left: bool,
    ) -> Result<Option<String>> {
        let mut cmd = redis::cmd("LMOVE");
        cmd.arg(source.into())
            .arg(destination.into())
            .arg(if from_left { "LEFT" } else { "RIGHT" })
            .arg(if to_left { "LEFT" } else { "RIGHT" });
        optional_string(&self.execute(&cmd).await?)
    }

    /// BRPOPLPUSH:阻塞版 RPOPLPUSH。
    pub async fn brpoplpush(
        &self,
        source: impl Into<String>,
        destination: impl Into<String>,
        timeout_seconds: i64,
    ) -> Result<Option<String>> {
        let mut cmd = redis::cmd("BRPOPLPUSH");
        cmd.arg(source.into())
            .arg(destination.into())
            .arg(timeout_seconds);
        optional_string(&self.execute(&cmd).await?)
    }

    /// LPOP key count。
    pub async fn lpop_count(&self, key: impl Into<String>, count: u64) -> Result<Vec<String>> {
        let mut cmd = redis::cmd("LPOP");
        cmd.arg(key.into()).arg(count);
        collect_string_array(&self.execute(&cmd).await?)
    }

    /// RPOP key count。
    pub async fn rpop_count(&self, key: impl Into<String>, count: u64) -> Result<Vec<String>> {
        let mut cmd = redis::cmd("RPOP");
        cmd.arg(key.into()).arg(count);
        collect_string_array(&self.execute(&cmd).await?)
    }

    /// LMPOP:从多个列表之一弹出一批元素。
    pub async fn lmpop(
        &self,
        keys: &[String],
        left: bool,
        count: u64,
    ) -> Result<Option<(String, Vec<String>)>> {
        if keys.is_empty() {
            return Ok(None);
        }
        let mut cmd = redis::cmd("LMPOP");
        cmd.arg(keys.len());
        for key in keys {
            cmd.arg(key);
        }
        cmd.arg(if left { "LEFT" } else { "RIGHT" }).arg("COUNT");
        cmd.arg(count);
        parse_pop_reply(&self.execute(&cmd).await?)
    }

    /// BLMPOP:阻塞版 LMPOP(超时 0 表示无限等待)。
    pub async fn blmpop(
        &self,
        timeout_seconds: f64,
        keys: &[String],
        left: bool,
        count: u64,
    ) -> Result<Option<(String, Vec<String>)>> {
        if keys.is_empty() {
            return Ok(None);
        }
        let mut cmd = redis::cmd("BLMPOP");
        cmd.arg(timeout_seconds).arg(keys.len());
        for key in keys {
            cmd.arg(key);
        }
        cmd.arg(if left { "LEFT" } else { "RIGHT" }).arg("COUNT");
        cmd.arg(count);
        parse_pop_reply(&self.execute(&cmd).await?)
    }

    // ==================== Sorted Set 补遗 ====================

    /// ZADD 带选项(不含 INCR)。
    pub async fn zadd_with_options(
        &self,
        key: impl Into<String>,
        members: &[(f64, String)],
        options: ZAddOptions,
    ) -> Result<i64> {
        if options.nx && options.xx {
            return Err(DbError::InvalidArgument(
                "ZADD 选项 NX 与 XX 不能同时使用".to_string(),
            ));
        }
        if options.gt && options.lt {
            return Err(DbError::InvalidArgument(
                "ZADD 选项 GT 与 LT 不能同时使用".to_string(),
            ));
        }
        if members.is_empty() {
            return Ok(0);
        }
        let mut cmd = redis::cmd("ZADD");
        cmd.arg(key.into());
        if options.nx {
            cmd.arg("NX");
        }
        if options.xx {
            cmd.arg("XX");
        }
        if options.gt {
            cmd.arg("GT");
        }
        if options.lt {
            cmd.arg("LT");
        }
        if options.ch {
            cmd.arg("CH");
        }
        for (score, member) in members {
            cmd.arg(score).arg(member);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// ZADD INCR:返回增加后的分数。
    pub async fn zadd_incr(
        &self,
        key: impl Into<String>,
        increment: f64,
        member: impl Into<String>,
    ) -> Result<Option<f64>> {
        let mut cmd = redis::cmd("ZADD");
        cmd.arg(key.into())
            .arg("INCR")
            .arg(increment)
            .arg(member.into());
        let result = self.execute(&cmd).await?;
        if result.is_nil() {
            return Ok(None);
        }
        result
            .as_f64()
            .or_else(|| result.as_string().and_then(|value| value.parse().ok()))
            .map(Some)
            .ok_or_else(|| DbError::RedisTypeConversionError("ZADD INCR 未返回分数".to_string()))
    }

    /// ZPOPMIN。
    pub async fn zpopmin(
        &self,
        key: impl Into<String>,
        count: Option<u64>,
    ) -> Result<Vec<(String, f64)>> {
        self.zpop("ZPOPMIN", key.into(), count).await
    }

    /// ZPOPMAX。
    pub async fn zpopmax(
        &self,
        key: impl Into<String>,
        count: Option<u64>,
    ) -> Result<Vec<(String, f64)>> {
        self.zpop("ZPOPMAX", key.into(), count).await
    }

    async fn zpop(
        &self,
        command: &str,
        key: String,
        count: Option<u64>,
    ) -> Result<Vec<(String, f64)>> {
        let mut cmd = redis::cmd(command);
        cmd.arg(key);
        if let Some(count) = count {
            cmd.arg(count);
        }
        parse_with_scores(&self.execute(&cmd).await?)
    }

    /// ZMSCORE:批量获取分数。
    pub async fn zmscore(
        &self,
        key: impl Into<String>,
        members: &[String],
    ) -> Result<Vec<Option<f64>>> {
        if members.is_empty() {
            return Ok(Vec::new());
        }
        let mut cmd = redis::cmd("ZMSCORE");
        cmd.arg(key.into());
        for member in members {
            cmd.arg(member);
        }
        let value = self.execute(&cmd).await?;
        let items = value
            .as_array()
            .ok_or_else(|| DbError::RedisTypeConversionError("ZMSCORE 结果不是数组".to_string()))?;
        Ok(items
            .iter()
            .map(|item| {
                if item.is_nil() {
                    None
                } else {
                    item.as_f64()
                        .or_else(|| item.as_string().and_then(|value| value.parse().ok()))
                }
            })
            .collect())
    }

    // ==================== 键管理补遗 ====================

    /// UNLINK:异步删除。
    pub async fn unlink(&self, keys: &[String]) -> Result<i64> {
        if keys.is_empty() {
            return Ok(0);
        }
        let mut cmd = redis::cmd("UNLINK");
        for key in keys {
            cmd.arg(key);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// TYPE。
    pub async fn key_type(&self, key: impl Into<String>) -> Result<String> {
        let mut cmd = redis::cmd("TYPE");
        cmd.arg(key.into());
        optional_string(&self.execute(&cmd).await?)
            .map(|value| value.unwrap_or_else(|| "none".to_string()))
    }

    /// RENAME。
    pub async fn rename(
        &self,
        source: impl Into<String>,
        destination: impl Into<String>,
    ) -> Result<()> {
        let mut cmd = redis::cmd("RENAME");
        cmd.arg(source.into()).arg(destination.into());
        self.execute(&cmd).await?;
        Ok(())
    }

    /// COPY(`replace=true` 覆盖目标)。
    pub async fn copy(
        &self,
        source: impl Into<String>,
        destination: impl Into<String>,
        replace: bool,
    ) -> Result<bool> {
        let mut cmd = redis::cmd("COPY");
        cmd.arg(source.into()).arg(destination.into());
        if replace {
            cmd.arg("REPLACE");
        }
        Ok(self.execute(&cmd).await?.as_i64() == Some(1))
    }

    /// TOUCH:更新访问时间。
    pub async fn touch(&self, keys: &[String]) -> Result<i64> {
        if keys.is_empty() {
            return Ok(0);
        }
        let mut cmd = redis::cmd("TOUCH");
        for key in keys {
            cmd.arg(key);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// PTTL。
    pub async fn pttl(&self, key: impl Into<String>) -> Result<i64> {
        let mut cmd = redis::cmd("PTTL");
        cmd.arg(key.into());
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(-1))
    }

    /// PEXPIRE。
    pub async fn pexpire(&self, key: impl Into<String>, milliseconds: i64) -> Result<bool> {
        let mut cmd = redis::cmd("PEXPIRE");
        cmd.arg(key.into()).arg(milliseconds);
        Ok(self.execute(&cmd).await?.as_i64() == Some(1))
    }

    // ==================== Bitmap ====================

    /// SETBIT。
    pub async fn setbit(&self, key: impl Into<String>, offset: u64, value: bool) -> Result<i64> {
        let mut cmd = redis::cmd("SETBIT");
        cmd.arg(key.into())
            .arg(offset)
            .arg(if value { 1 } else { 0 });
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// GETBIT。
    pub async fn getbit(&self, key: impl Into<String>, offset: u64) -> Result<bool> {
        let mut cmd = redis::cmd("GETBIT");
        cmd.arg(key.into()).arg(offset);
        Ok(self.execute(&cmd).await?.as_i64() == Some(1))
    }

    /// BITCOUNT(可选字节范围)。
    pub async fn bitcount(&self, key: impl Into<String>, range: Option<(i64, i64)>) -> Result<i64> {
        let mut cmd = redis::cmd("BITCOUNT");
        cmd.arg(key.into());
        if let Some((start, end)) = range {
            cmd.arg(start).arg(end);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// BITOP。
    pub async fn bitop(
        &self,
        operation: &str,
        destination: impl Into<String>,
        sources: &[String],
    ) -> Result<i64> {
        if sources.is_empty() {
            return Err(DbError::InvalidArgument(
                "BITOP 至少需要一个源 key".to_string(),
            ));
        }
        let mut cmd = redis::cmd("BITOP");
        cmd.arg(operation).arg(destination.into());
        for source in sources {
            cmd.arg(source);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    // ==================== HyperLogLog ====================

    /// PFADD。
    pub async fn pfadd(&self, key: impl Into<String>, elements: &[String]) -> Result<i64> {
        if elements.is_empty() {
            return Ok(0);
        }
        let mut cmd = redis::cmd("PFADD");
        cmd.arg(key.into());
        for element in elements {
            cmd.arg(element);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// PFCOUNT。
    pub async fn pfcount(&self, keys: &[String]) -> Result<i64> {
        if keys.is_empty() {
            return Ok(0);
        }
        let mut cmd = redis::cmd("PFCOUNT");
        for key in keys {
            cmd.arg(key);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// PFMERGE。
    pub async fn pfmerge(&self, destination: impl Into<String>, sources: &[String]) -> Result<()> {
        let mut cmd = redis::cmd("PFMERGE");
        cmd.arg(destination.into());
        for source in sources {
            cmd.arg(source);
        }
        self.execute(&cmd).await?;
        Ok(())
    }

    // ==================== GEO ====================

    /// GEOADD(经度、纬度、成员)。
    pub async fn geoadd(
        &self,
        key: impl Into<String>,
        members: &[(f64, f64, String)],
    ) -> Result<i64> {
        if members.is_empty() {
            return Ok(0);
        }
        let mut cmd = redis::cmd("GEOADD");
        cmd.arg(key.into());
        for (longitude, latitude, member) in members {
            cmd.arg(longitude).arg(latitude).arg(member);
        }
        Ok(self.execute(&cmd).await?.as_i64().unwrap_or(0))
    }

    /// GEOPOS:批量获取坐标。
    pub async fn geopos(
        &self,
        key: impl Into<String>,
        members: &[String],
    ) -> Result<Vec<Option<(f64, f64)>>> {
        if members.is_empty() {
            return Ok(Vec::new());
        }
        let mut cmd = redis::cmd("GEOPOS");
        cmd.arg(key.into());
        for member in members {
            cmd.arg(member);
        }
        let value = self.execute(&cmd).await?;
        let items = value
            .as_array()
            .ok_or_else(|| DbError::RedisTypeConversionError("GEOPOS 结果不是数组".to_string()))?;
        items
            .iter()
            .map(|item| {
                if item.is_nil() {
                    return Ok(None);
                }
                let pair = item.as_array().ok_or_else(|| {
                    DbError::RedisTypeConversionError("GEOPOS 坐标不是数组".to_string())
                })?;
                if pair.len() != 2 {
                    return Ok(None);
                }
                let longitude = pair[0].as_f64().ok_or_else(|| {
                    DbError::RedisTypeConversionError("GEOPOS 经度不是数字".to_string())
                })?;
                let latitude = pair[1].as_f64().ok_or_else(|| {
                    DbError::RedisTypeConversionError("GEOPOS 纬度不是数字".to_string())
                })?;
                Ok(Some((longitude, latitude)))
            })
            .collect()
    }

    /// GEODIST(单位 m/km/mi/ft)。
    pub async fn geodist(
        &self,
        key: impl Into<String>,
        member1: impl Into<String>,
        member2: impl Into<String>,
        unit: Option<&str>,
    ) -> Result<Option<f64>> {
        let mut cmd = redis::cmd("GEODIST");
        cmd.arg(key.into()).arg(member1.into()).arg(member2.into());
        if let Some(unit) = unit {
            cmd.arg(unit);
        }
        let result = self.execute(&cmd).await?;
        if result.is_nil() {
            return Ok(None);
        }
        result
            .as_f64()
            .or_else(|| result.as_string().and_then(|value| value.parse().ok()))
            .map(Some)
            .ok_or_else(|| DbError::RedisTypeConversionError("GEODIST 未返回数字".to_string()))
    }

    /// GEOSEARCH BYRADIUS,返回命中成员(按距离升序)。
    pub async fn geosearch_radius(
        &self,
        key: impl Into<String>,
        longitude: f64,
        latitude: f64,
        radius: f64,
        unit: &str,
    ) -> Result<Vec<String>> {
        let mut cmd = redis::cmd("GEOSEARCH");
        cmd.arg(key.into())
            .arg("FROMLONLAT")
            .arg(longitude)
            .arg(latitude)
            .arg("BYRADIUS")
            .arg(radius)
            .arg(unit)
            .arg("ASC");
        collect_string_array(&self.execute(&cmd).await?)
    }
}

/// 根据 SET 回复与选项判断条件写是否生效。
///
/// 未开启 `GET` 时:`+OK`(非 `nil`)表示写入,`nil` 表示 `NX`/`XX`
/// 条件不满足。开启 `GET` 时 Redis 一律返回旧值(key 不存在则 `nil`),
/// 需要按条件语义反推:`NX` 下 `nil` 表示旧 key 不存在(写入成功),
/// `XX` 下 `nil` 表示旧 key 不存在(未写入);未指定条件时 `SET` 总会写入。
fn classify_set_outcome(result: &crate::RedisValue, options: &SetOptions) -> SetOutcome {
    let applied = if options.get {
        let old_exists = !result.is_nil();
        match (options.nx, options.xx) {
            (true, false) => !old_exists,
            (false, true) => old_exists,
            _ => true,
        }
    } else {
        !result.is_nil()
    };
    if applied {
        SetOutcome::Applied
    } else {
        SetOutcome::NotApplied
    }
}

fn parse_pop_reply(value: &crate::RedisValue) -> Result<Option<(String, Vec<String>)>> {
    let Some(items) = value.as_array() else {
        return Ok(None);
    };
    if items.is_empty() {
        return Ok(None);
    }
    let key = items[0].as_string().ok_or_else(|| {
        DbError::RedisTypeConversionError("LMPOP 返回的 key 不是字符串".to_string())
    })?;
    let values = collect_string_array(&items[1])?;
    Ok(Some((key, values)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::RedisValue;

    fn options(nx: bool, xx: bool, get: bool) -> SetOptions {
        SetOptions {
            nx,
            xx,
            get,
            ..SetOptions::default()
        }
    }

    #[test]
    fn set_outcome_without_get_uses_nil_to_detect_not_applied() {
        // RED 场景:SET NX 命中已存在的 key 时 Redis 只返回 nil,
        // 旧接口把 +OK 与 nil 都折叠成 Ok(None),调用方无法得知
        // 本次写入被跳过。这里锁定 get=false 的判读规则:非 nil 即生效。
        assert_eq!(
            classify_set_outcome(&RedisValue::Bool(true), &options(true, false, false)),
            SetOutcome::Applied
        );
        assert_eq!(
            classify_set_outcome(&RedisValue::Nil, &options(true, false, false)),
            SetOutcome::NotApplied
        );
        assert_eq!(
            classify_set_outcome(&RedisValue::Bool(true), &options(false, true, false)),
            SetOutcome::Applied
        );
        assert_eq!(
            classify_set_outcome(&RedisValue::Nil, &options(false, true, false)),
            SetOutcome::NotApplied
        );
    }

    #[test]
    fn set_outcome_with_get_distinguishes_nx_and_xx() {
        // RED 场景:开启 GET 后 nil 不再等价于「未写入」——NX 下 nil
        // 表示旧 key 不存在(写入成功),XX 下 nil 表示旧 key 缺失
        // (未写入)。旧接口把两种情况都折叠成 Ok(None)。
        let old = RedisValue::String("old".to_string());

        // NX + GET:nil 才是写入成功,返回旧值说明 key 已存在、未写入。
        assert_eq!(
            classify_set_outcome(&RedisValue::Nil, &options(true, false, true)),
            SetOutcome::Applied
        );
        assert_eq!(
            classify_set_outcome(&old, &options(true, false, true)),
            SetOutcome::NotApplied
        );

        // XX + GET:返回旧值说明 key 存在、写入成功;nil 说明 key 缺失、未写入。
        assert_eq!(
            classify_set_outcome(&old, &options(false, true, true)),
            SetOutcome::Applied
        );
        assert_eq!(
            classify_set_outcome(&RedisValue::Nil, &options(false, true, true)),
            SetOutcome::NotApplied
        );

        // 无 NX/XX 时 SET 总会写入,GET 只是顺带返回旧值。
        assert_eq!(
            classify_set_outcome(&RedisValue::Nil, &options(false, false, true)),
            SetOutcome::Applied
        );
        assert_eq!(
            classify_set_outcome(&old, &options(false, false, true)),
            SetOutcome::Applied
        );
    }
}