unistore-sqlite 0.1.0

SQLite embedded database capability for UniStore
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
//! 查询构建器
//!
//! 职责:提供流畅的 SQL 查询构建 API

use crate::connection::Connection;
use crate::error::SqliteError;
use crate::types::{Param, Row, Rows};

/// SELECT 查询构建器
pub struct SelectBuilder<'a> {
    conn: &'a Connection,
    table: String,
    columns: Vec<String>,
    where_clause: Option<String>,
    where_params: Vec<Param>,
    order_by: Option<String>,
    limit: Option<usize>,
    offset: Option<usize>,
}

impl<'a> SelectBuilder<'a> {
    /// 创建新的 SELECT 构建器
    pub fn new(conn: &'a Connection, table: impl Into<String>) -> Self {
        Self {
            conn,
            table: table.into(),
            columns: vec!["*".to_string()],
            where_clause: None,
            where_params: Vec::new(),
            order_by: None,
            limit: None,
            offset: None,
        }
    }

    /// 指定要查询的列
    pub fn columns(mut self, cols: &[&str]) -> Self {
        self.columns = cols.iter().map(|s| s.to_string()).collect();
        self
    }

    /// 添加 WHERE 条件
    pub fn filter(mut self, condition: &str, params: impl IntoIterator<Item = Param>) -> Self {
        self.where_clause = Some(condition.to_string());
        self.where_params = params.into_iter().collect();
        self
    }

    /// 添加 WHERE 条件(单参数便捷方法)
    pub fn filter_eq(self, column: &str, value: impl Into<Param>) -> Self {
        self.filter(&format!("{} = ?", column), [value.into()])
    }

    /// 添加 ORDER BY
    pub fn order_by(mut self, column: &str, desc: bool) -> Self {
        let direction = if desc { "DESC" } else { "ASC" };
        self.order_by = Some(format!("{} {}", column, direction));
        self
    }

    /// 设置 LIMIT
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// 设置 OFFSET
    pub fn offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }

    /// 构建 SQL 语句
    pub fn build(&self) -> (String, Vec<Param>) {
        let mut sql = format!("SELECT {} FROM {}", self.columns.join(", "), self.table);

        let params = self.where_params.clone();

        if let Some(ref where_clause) = self.where_clause {
            sql.push_str(" WHERE ");
            sql.push_str(where_clause);
        }

        if let Some(ref order) = self.order_by {
            sql.push_str(" ORDER BY ");
            sql.push_str(order);
        }

        if let Some(limit) = self.limit {
            sql.push_str(&format!(" LIMIT {}", limit));
        }

        if let Some(offset) = self.offset {
            sql.push_str(&format!(" OFFSET {}", offset));
        }

        (sql, params)
    }

    /// 执行查询,返回所有行
    pub fn fetch_all(self) -> Result<Rows, SqliteError> {
        let (sql, params) = self.build();
        self.conn.query(&sql, &params)
    }

    /// 执行查询,返回第一行
    pub fn fetch_one(self) -> Result<Option<Row>, SqliteError> {
        let (sql, params) = self.build();
        self.conn.query_row(&sql, &params)
    }

    /// 执行查询,返回行数
    pub fn count(self) -> Result<i64, SqliteError> {
        let sql = format!(
            "SELECT COUNT(*) as cnt FROM {}{}",
            self.table,
            self.where_clause
                .as_ref()
                .map(|w| format!(" WHERE {}", w))
                .unwrap_or_default()
        );
        let row = self.conn.query_row(&sql, &self.where_params)?;
        Ok(row.and_then(|r| r.get_i64("cnt")).unwrap_or(0))
    }
}

/// INSERT 查询构建器
pub struct InsertBuilder<'a> {
    conn: &'a Connection,
    table: String,
    columns: Vec<String>,
    values: Vec<Param>,
}

impl<'a> InsertBuilder<'a> {
    /// 创建新的 INSERT 构建器
    pub fn new(conn: &'a Connection, table: impl Into<String>) -> Self {
        Self {
            conn,
            table: table.into(),
            columns: Vec::new(),
            values: Vec::new(),
        }
    }

    /// 设置列值
    pub fn set(mut self, column: &str, value: impl Into<Param>) -> Self {
        self.columns.push(column.to_string());
        self.values.push(value.into());
        self
    }

    /// 构建 SQL 语句
    pub fn build(&self) -> (String, Vec<Param>) {
        let placeholders = vec!["?"; self.columns.len()].join(", ");
        let sql = format!(
            "INSERT INTO {} ({}) VALUES ({})",
            self.table,
            self.columns.join(", "),
            placeholders
        );
        (sql, self.values.clone())
    }

    /// 执行插入,返回最后插入的行 ID
    pub fn execute(self) -> Result<i64, SqliteError> {
        let (sql, params) = self.build();
        self.conn.execute(&sql, &params)?;
        self.conn.last_insert_rowid()
    }
}

/// UPDATE 查询构建器
pub struct UpdateBuilder<'a> {
    conn: &'a Connection,
    table: String,
    sets: Vec<(String, Param)>,
    where_clause: Option<String>,
    where_params: Vec<Param>,
}

impl<'a> UpdateBuilder<'a> {
    /// 创建新的 UPDATE 构建器
    pub fn new(conn: &'a Connection, table: impl Into<String>) -> Self {
        Self {
            conn,
            table: table.into(),
            sets: Vec::new(),
            where_clause: None,
            where_params: Vec::new(),
        }
    }

    /// 设置列值
    pub fn set(mut self, column: &str, value: impl Into<Param>) -> Self {
        self.sets.push((column.to_string(), value.into()));
        self
    }

    /// 添加 WHERE 条件
    pub fn filter(mut self, condition: &str, params: impl IntoIterator<Item = Param>) -> Self {
        self.where_clause = Some(condition.to_string());
        self.where_params = params.into_iter().collect();
        self
    }

    /// 添加 WHERE 条件(单参数便捷方法)
    pub fn filter_eq(self, column: &str, value: impl Into<Param>) -> Self {
        self.filter(&format!("{} = ?", column), [value.into()])
    }

    /// 构建 SQL 语句
    pub fn build(&self) -> (String, Vec<Param>) {
        let set_clause: Vec<String> = self.sets.iter().map(|(col, _)| format!("{} = ?", col)).collect();

        let mut sql = format!("UPDATE {} SET {}", self.table, set_clause.join(", "));

        let mut params: Vec<Param> = self.sets.iter().map(|(_, v)| v.clone()).collect();

        if let Some(ref where_clause) = self.where_clause {
            sql.push_str(" WHERE ");
            sql.push_str(where_clause);
            params.extend(self.where_params.clone());
        }

        (sql, params)
    }

    /// 执行更新,返回影响的行数
    pub fn execute(self) -> Result<usize, SqliteError> {
        let (sql, params) = self.build();
        self.conn.execute(&sql, &params)
    }
}

/// DELETE 查询构建器
pub struct DeleteBuilder<'a> {
    conn: &'a Connection,
    table: String,
    where_clause: Option<String>,
    where_params: Vec<Param>,
}

impl<'a> DeleteBuilder<'a> {
    /// 创建新的 DELETE 构建器
    pub fn new(conn: &'a Connection, table: impl Into<String>) -> Self {
        Self {
            conn,
            table: table.into(),
            where_clause: None,
            where_params: Vec::new(),
        }
    }

    /// 添加 WHERE 条件
    pub fn filter(mut self, condition: &str, params: impl IntoIterator<Item = Param>) -> Self {
        self.where_clause = Some(condition.to_string());
        self.where_params = params.into_iter().collect();
        self
    }

    /// 添加 WHERE 条件(单参数便捷方法)
    pub fn filter_eq(self, column: &str, value: impl Into<Param>) -> Self {
        self.filter(&format!("{} = ?", column), [value.into()])
    }

    /// 构建 SQL 语句
    pub fn build(&self) -> (String, Vec<Param>) {
        let mut sql = format!("DELETE FROM {}", self.table);

        if let Some(ref where_clause) = self.where_clause {
            sql.push_str(" WHERE ");
            sql.push_str(where_clause);
        }

        (sql, self.where_params.clone())
    }

    /// 执行删除,返回影响的行数
    pub fn execute(self) -> Result<usize, SqliteError> {
        let (sql, params) = self.build();
        self.conn.execute(&sql, &params)
    }
}

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

    fn setup_test_db() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE users (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                age INTEGER
            )",
        )
        .unwrap();
        conn
    }

    #[test]
    fn test_insert() {
        let conn = setup_test_db();

        let id = InsertBuilder::new(&conn, "users")
            .set("name", "Alice")
            .set("age", 30)
            .execute()
            .unwrap();

        assert_eq!(id, 1);
    }

    #[test]
    fn test_select() {
        let conn = setup_test_db();

        InsertBuilder::new(&conn, "users")
            .set("name", "Alice")
            .set("age", 30)
            .execute()
            .unwrap();

        InsertBuilder::new(&conn, "users")
            .set("name", "Bob")
            .set("age", 25)
            .execute()
            .unwrap();

        // 查询所有
        let rows = SelectBuilder::new(&conn, "users").fetch_all().unwrap();
        assert_eq!(rows.len(), 2);

        // 条件查询
        let rows = SelectBuilder::new(&conn, "users")
            .filter_eq("name", "Alice")
            .fetch_all()
            .unwrap();
        assert_eq!(rows.len(), 1);

        // 排序和限制
        let rows = SelectBuilder::new(&conn, "users")
            .order_by("age", false)
            .limit(1)
            .fetch_all()
            .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].get_str("name"), Some("Bob"));
    }

    #[test]
    fn test_update() {
        let conn = setup_test_db();

        InsertBuilder::new(&conn, "users")
            .set("name", "Alice")
            .set("age", 30)
            .execute()
            .unwrap();

        let affected = UpdateBuilder::new(&conn, "users")
            .set("age", 31)
            .filter_eq("name", "Alice")
            .execute()
            .unwrap();

        assert_eq!(affected, 1);

        let row = SelectBuilder::new(&conn, "users")
            .filter_eq("name", "Alice")
            .fetch_one()
            .unwrap()
            .unwrap();

        assert_eq!(row.get_i64("age"), Some(31));
    }

    #[test]
    fn test_delete() {
        let conn = setup_test_db();

        InsertBuilder::new(&conn, "users")
            .set("name", "Alice")
            .set("age", 30)
            .execute()
            .unwrap();

        InsertBuilder::new(&conn, "users")
            .set("name", "Bob")
            .set("age", 25)
            .execute()
            .unwrap();

        let affected = DeleteBuilder::new(&conn, "users")
            .filter_eq("name", "Alice")
            .execute()
            .unwrap();

        assert_eq!(affected, 1);

        let count = SelectBuilder::new(&conn, "users").count().unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_count() {
        let conn = setup_test_db();

        for i in 0..5 {
            InsertBuilder::new(&conn, "users")
                .set("name", format!("User{}", i))
                .set("age", 20 + i)
                .execute()
                .unwrap();
        }

        let count = SelectBuilder::new(&conn, "users").count().unwrap();
        assert_eq!(count, 5);

        let count = SelectBuilder::new(&conn, "users")
            .filter("age >= ?", [22i32.into()])
            .count()
            .unwrap();
        assert_eq!(count, 3);
    }
}