cache_any/caches/
mysql.rs

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
use std::sync::Arc;
use crate::{Cache, Cacheable};

/// [`MySqlCache`] is a cache using mysql to store data.
/// 
/// It uses [`sqlx::MySqlPool`] to connect to mysql.
/// Feature `mysql` must be enabled.
/// 
/// ## Prepare
/// 
/// Create a table named `cache` with the following schema:
/// 
/// ```sql
/// CREATE TABLE IF NOT EXISTS cache (
///     name varchar(255) not null,
///     val text not null,
///     primary key (name)
/// );
/// ```
/// 
/// **Note**:
/// 1. You can change the table name and the field names.
/// 2. The `name` field (or whatever you specify) is the primary key of the cache.
/// 
/// ## Build
/// 
/// Use [`MySqlCacheBuilder`] to build a [`MySqlCache`].
/// You need to specify the table name and the field names when building.
/// 
/// ```rust,ignore
/// let pool = MySqlPool::connect("mysql://test:123456@127.0.0.1:3306/dev").await?;
/// let cache = MySqlCacheBuilder::new(pool)
///     .table("cache")
///     .key_field("name")
///     .value_field("val")
///     .finish();
/// ```
/// 
#[derive(Debug, Clone)]
pub struct MySqlCache {
    inner: Arc<Inner>,
}

#[async_trait::async_trait]
impl Cache for MySqlCache {
    async fn get<T: Cacheable + Send + Sync>(&self, key: &str) -> anyhow::Result<Option<T>> {
        let sql = format!(r#"
            SELECT {}
            FROM {}
            WHERE {} = ?
            LIMIT 1
        "#, &self.inner.value_field, &self.inner.table, &self.inner.key_field);

        let value: Option<(String,)> = sqlx::query_as(&sql)
            .bind(key)
            .fetch_optional(&self.inner.pool)
            .await?;

        let result = value.as_ref()
            .map(|value| &value.0)
            .map(|value| value.as_str())
            .map(T::from_hex)
            .transpose()?;

        Ok(result)
    }

    async fn set<T: Cacheable + Send + Sync>(&self, key: &str, value: T) -> anyhow::Result<()> {
        let value = value.to_hex();

        let sql = format!(r#"
            INSERT INTO {} ({}, {})
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE {} = ?
        "#,
            &self.inner.table,
            &self.inner.key_field,
            &self.inner.value_field,
            &self.inner.value_field,
        );

        sqlx::query(&sql)
            .bind(key)
            .bind(&value)
            .bind(&value)
            .execute(&self.inner.pool)
            .await?;

        Ok(())
    }

    async fn delete(&self, key: &str) -> anyhow::Result<()> {
        let sql = format!(r#"
            DELETE FROM {}
            WHERE {} = ?
        "#, &self.inner.table, &self.inner.key_field);

        sqlx::query(&sql)
            .bind(key)
            .execute(&self.inner.pool)
            .await?;

        Ok(())
    }

    async fn len(&self) -> anyhow::Result<usize> {
        let sql = format!(r#"
            SELECT COUNT(*)
            FROM {}
        "#, &self.inner.table);

        let count: (i64,) = sqlx::query_as(&sql).fetch_optional(&self.inner.pool).await?.unwrap_or_default();

        Ok(count.0 as usize)
    }
}

/// [`MySqlCacheBuilder`] is used to build a [`MySqlCache`].
#[derive(Debug, Clone)]
pub struct MySqlCacheBuilder {
    key_field: String,
    value_field: String,
    table: String,
    pool: sqlx::MySqlPool,
}

impl MySqlCacheBuilder {
    /// Create a new [`MySqlCacheBuilder`]. You need to specify the [`sqlx::MySqlPool`].
    pub fn new(pool: sqlx::MySqlPool) -> Self {
        Self {
            key_field: String::from("name"),
            value_field: String::from("val"),
            table: String::from("cache"),
            pool,
        }
    }

    /// Set the key field.
    pub fn key_field<S: ToString>(mut self, key: S) -> Self {
        self.key_field = key.to_string();
        self
    }

    /// Set the value field.
    pub fn value_field<S: ToString>(mut self, value: S) -> Self {
        self.value_field = value.to_string();
        self
    }

    /// Set the table name.
    pub fn table<S: ToString>(mut self, table: S) -> Self {
        self.table = table.to_string();
        self
    }

    /// Finish and build a [`MySqlCache`].
    pub fn finish(self) -> MySqlCache {
        MySqlCache {
            inner: Arc::new(Inner {
                key_field: self.key_field,
                value_field: self.value_field,
                table: self.table,
                pool: self.pool,
            })
        }
    }
}

#[derive(Debug)]
struct Inner {
    key_field: String,
    value_field: String,
    table: String,
    pool: sqlx::MySqlPool,
}

#[cfg(test)]
mod tests {
    use sqlx::MySqlPool;
    use super::*;

    #[tokio::test]
    async fn test_mysql_cache_builder() -> anyhow::Result<()> {
        let pool = MySqlPool::connect("mysql://test:123456@127.0.0.1:3306/dev").await?;
        let cache = MySqlCacheBuilder::new(pool)
            .table("my_cache")
            .key_field("name")
            .value_field("val")
            .finish();

        assert_eq!(cache.inner.table, String::from("my_cache"));
        assert_eq!(cache.inner.key_field, String::from("name"));
        assert_eq!(cache.inner.value_field, String::from("val"));

        let cloned_cache = cache.clone();
        assert_eq!(cloned_cache.inner.table, String::from("my_cache"));
        assert_eq!(cloned_cache.inner.key_field, String::from("name"));
        assert_eq!(cloned_cache.inner.value_field, String::from("val"));

        println!("{:?}", cloned_cache);

        Ok(())
    }

    #[tokio::test]
    async fn test_mysql_cache() -> anyhow::Result<()> {
        // create user test@'%' identified by '123456';
        // create database dev;
        // grant all privileges on dev.* to test@'%';
        //
        // CREATE TABLE IF NOT EXISTS my_cache (
        //     name varchar(255) not null,
        //     val text not null,
        //     primary key (name)
        // );

        let pool = MySqlPool::connect("mysql://test:123456@127.0.0.1:3306/dev").await?;

        let cache = MySqlCacheBuilder::new(pool)
            .table("my_cache")
            .key_field("name")
            .value_field("val")
            .finish();

        cache.set("user_id", 114514).await?;
        cache.set("username", String::from("jack")).await?;

        let user_id: usize = cache.get("user_id").await?.unwrap();
        let username: String = cache.get("username").await?.unwrap();

        assert_eq!(user_id, 114514);
        assert_eq!(username, String::from("jack"));

        cache.delete("user_id").await?;
        let user_id: Option<()> = cache.get("user_id").await?;
        assert_eq!(user_id, None);

        let len = cache.len().await?;
        println!("len = {}", len);

        Ok(())
    }
}