xdl_database/drivers/
redis_driver.rs

1//! Redis driver
2
3use crate::{DatabaseError, DatabaseResult, Recordset};
4use redis::aio::ConnectionManager;
5use redis::{AsyncCommands, Client};
6
7pub struct RedisConnection {
8    conn: Option<ConnectionManager>,
9}
10
11impl std::fmt::Debug for RedisConnection {
12    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13        f.debug_struct("RedisConnection")
14            .field("conn", &self.conn.is_some())
15            .finish()
16    }
17}
18
19impl RedisConnection {
20    pub async fn connect(connection_string: &str) -> DatabaseResult<Self> {
21        let client = Client::open(connection_string)?;
22        let conn = ConnectionManager::new(client).await?;
23
24        Ok(Self { conn: Some(conn) })
25    }
26
27    pub async fn execute(&self, _query: &str) -> DatabaseResult<Recordset> {
28        // Redis doesn't have traditional SQL queries
29        // Return empty recordset for now
30        Ok(Recordset::empty())
31    }
32
33    pub async fn execute_command(&self, command: &str) -> DatabaseResult<u64> {
34        let mut conn = self
35            .conn
36            .as_ref()
37            .ok_or(DatabaseError::NotConnected)?
38            .clone();
39
40        // Parse Redis command (simplified)
41        let parts: Vec<&str> = command.split_whitespace().collect();
42        if parts.is_empty() {
43            return Err(DatabaseError::query_error("Empty command"));
44        }
45
46        // Execute command based on type
47        match parts[0].to_uppercase().as_str() {
48            "SET" if parts.len() >= 3 => {
49                let _: () = conn.set(parts[1], parts[2]).await?;
50                Ok(1)
51            }
52            "DEL" if parts.len() >= 2 => {
53                let count: u64 = conn.del(parts[1]).await?;
54                Ok(count)
55            }
56            _ => Ok(0),
57        }
58    }
59
60    pub async fn close(&mut self) -> DatabaseResult<()> {
61        self.conn = None;
62        Ok(())
63    }
64
65    pub async fn is_connected(&self) -> bool {
66        self.conn.is_some()
67    }
68}