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
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
//! 数据库迁移系统
//!
//! 职责:管理数据库 schema 版本和迁移

use crate::connection::Connection;
use crate::error::SqliteError;

/// 迁移信息
#[derive(Debug, Clone)]
pub struct Migration {
    /// 版本号
    pub version: u32,
    /// 迁移描述
    pub description: String,
    /// SQL 语句
    pub sql: String,
}

impl Migration {
    /// 创建新迁移
    pub fn new(version: u32, description: impl Into<String>, sql: impl Into<String>) -> Self {
        Self {
            version,
            description: description.into(),
            sql: sql.into(),
        }
    }
}

/// 迁移报告
#[derive(Debug, Default)]
pub struct MigrationReport {
    /// 已应用的迁移数量
    pub applied: usize,
    /// 跳过的迁移数量(已存在)
    pub skipped: usize,
    /// 当前数据库版本
    pub current_version: u32,
}

/// 表构建器
pub struct TableBuilder {
    name: String,
    columns: Vec<String>,
}

impl TableBuilder {
    /// 创建新的表构建器
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            columns: Vec::new(),
        }
    }

    /// 添加自增主键 id
    pub fn id(mut self) -> Self {
        self.columns
            .push("id INTEGER PRIMARY KEY AUTOINCREMENT".to_string());
        self
    }

    /// 添加整数列
    pub fn integer(mut self, name: &str) -> Self {
        self.columns.push(format!("{} INTEGER", name));
        self
    }

    /// 添加非空整数列
    pub fn integer_not_null(mut self, name: &str) -> Self {
        self.columns.push(format!("{} INTEGER NOT NULL", name));
        self
    }

    /// 添加带默认值的整数列
    pub fn integer_default(mut self, name: &str, default: i64) -> Self {
        self.columns
            .push(format!("{} INTEGER DEFAULT {}", name, default));
        self
    }

    /// 添加文本列
    pub fn text(mut self, name: &str) -> Self {
        self.columns.push(format!("{} TEXT", name));
        self
    }

    /// 添加非空文本列
    pub fn text_not_null(mut self, name: &str) -> Self {
        self.columns.push(format!("{} TEXT NOT NULL", name));
        self
    }

    /// 添加带默认值的文本列
    pub fn text_default(mut self, name: &str, default: &str) -> Self {
        self.columns
            .push(format!("{} TEXT DEFAULT '{}'", name, default));
        self
    }

    /// 添加实数列
    pub fn real(mut self, name: &str) -> Self {
        self.columns.push(format!("{} REAL", name));
        self
    }

    /// 添加非空实数列
    pub fn real_not_null(mut self, name: &str) -> Self {
        self.columns.push(format!("{} REAL NOT NULL", name));
        self
    }

    /// 添加二进制列
    pub fn blob(mut self, name: &str) -> Self {
        self.columns.push(format!("{} BLOB", name));
        self
    }

    /// 添加布尔列(存储为 INTEGER)
    pub fn boolean(mut self, name: &str) -> Self {
        self.columns.push(format!("{} INTEGER", name));
        self
    }

    /// 添加布尔列带默认值
    pub fn boolean_default(mut self, name: &str, default: bool) -> Self {
        self.columns
            .push(format!("{} INTEGER DEFAULT {}", name, if default { 1 } else { 0 }));
        self
    }

    /// 添加 created_at 时间戳列
    pub fn created_at(mut self) -> Self {
        self.columns
            .push("created_at TEXT DEFAULT (datetime('now'))".to_string());
        self
    }

    /// 添加 updated_at 时间戳列
    pub fn updated_at(mut self) -> Self {
        self.columns
            .push("updated_at TEXT DEFAULT (datetime('now'))".to_string());
        self
    }

    /// 添加时间戳列(created_at + updated_at)
    pub fn timestamps(self) -> Self {
        self.created_at().updated_at()
    }

    /// 添加外键
    pub fn foreign_key(mut self, column: &str, ref_table: &str, ref_column: &str) -> Self {
        self.columns.push(format!(
            "FOREIGN KEY ({}) REFERENCES {}({})",
            column, ref_table, ref_column
        ));
        self
    }

    /// 添加唯一约束
    pub fn unique(mut self, columns: &[&str]) -> Self {
        self.columns
            .push(format!("UNIQUE ({})", columns.join(", ")));
        self
    }

    /// 添加自定义列定义
    pub fn column(mut self, definition: &str) -> Self {
        self.columns.push(definition.to_string());
        self
    }

    /// 构建 CREATE TABLE 语句
    pub fn build(&self) -> String {
        format!(
            "CREATE TABLE IF NOT EXISTS {} (\n  {}\n)",
            self.name,
            self.columns.join(",\n  ")
        )
    }
}

/// Schema 构建器
pub struct SchemaBuilder {
    statements: Vec<String>,
}

impl SchemaBuilder {
    /// 创建新的 schema 构建器
    pub fn new() -> Self {
        Self {
            statements: Vec::new(),
        }
    }

    /// 创建表
    pub fn create_table<F>(&mut self, name: &str, f: F) -> Result<(), SqliteError>
    where
        F: FnOnce(TableBuilder) -> TableBuilder,
    {
        let builder = TableBuilder::new(name);
        let builder = f(builder);
        self.statements.push(builder.build());
        Ok(())
    }

    /// 创建索引
    pub fn create_index(&mut self, name: &str, table: &str, columns: &[&str]) -> Result<(), SqliteError> {
        self.statements.push(format!(
            "CREATE INDEX IF NOT EXISTS {} ON {} ({})",
            name,
            table,
            columns.join(", ")
        ));
        Ok(())
    }

    /// 创建唯一索引
    pub fn create_unique_index(
        &mut self,
        name: &str,
        table: &str,
        columns: &[&str],
    ) -> Result<(), SqliteError> {
        self.statements.push(format!(
            "CREATE UNIQUE INDEX IF NOT EXISTS {} ON {} ({})",
            name,
            table,
            columns.join(", ")
        ));
        Ok(())
    }

    /// 删除表
    pub fn drop_table(&mut self, name: &str) -> Result<(), SqliteError> {
        self.statements.push(format!("DROP TABLE IF EXISTS {}", name));
        Ok(())
    }

    /// 删除索引
    pub fn drop_index(&mut self, name: &str) -> Result<(), SqliteError> {
        self.statements.push(format!("DROP INDEX IF EXISTS {}", name));
        Ok(())
    }

    /// 添加原始 SQL
    pub fn raw(&mut self, sql: &str) -> Result<(), SqliteError> {
        self.statements.push(sql.to_string());
        Ok(())
    }

    /// 构建所有语句
    pub fn build(&self) -> String {
        self.statements.join(";\n")
    }
}

impl Default for SchemaBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// 迁移构建器
pub struct MigrationBuilder {
    migrations: Vec<Migration>,
}

impl MigrationBuilder {
    /// 创建新的迁移构建器
    pub fn new() -> Self {
        Self {
            migrations: Vec::new(),
        }
    }

    /// 添加版本迁移
    pub fn version<F>(&mut self, version: u32, description: &str, f: F)
    where
        F: FnOnce(&mut SchemaBuilder) -> Result<(), SqliteError>,
    {
        let mut schema = SchemaBuilder::new();
        if f(&mut schema).is_ok() {
            self.migrations.push(Migration::new(version, description, schema.build()));
        }
    }

    /// 获取所有迁移
    pub fn build(self) -> Vec<Migration> {
        self.migrations
    }
}

impl Default for MigrationBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// 迁移执行器
pub struct Migrator<'a> {
    conn: &'a Connection,
}

impl<'a> Migrator<'a> {
    /// 创建新的迁移执行器
    pub fn new(conn: &'a Connection) -> Self {
        Self { conn }
    }

    /// 确保迁移表存在
    fn ensure_migration_table(&self) -> Result<(), SqliteError> {
        self.conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS _migrations (
                version INTEGER PRIMARY KEY,
                description TEXT NOT NULL,
                applied_at TEXT DEFAULT (datetime('now'))
            )",
        )
    }

    /// 获取当前版本
    pub fn current_version(&self) -> Result<u32, SqliteError> {
        self.ensure_migration_table()?;

        let row = self
            .conn
            .query_row("SELECT MAX(version) as v FROM _migrations", &[])?;

        Ok(row.and_then(|r| r.get_i64("v")).unwrap_or(0) as u32)
    }

    /// 检查迁移是否已应用
    pub fn is_applied(&self, version: u32) -> Result<bool, SqliteError> {
        self.ensure_migration_table()?;

        let row = self.conn.query_row(
            "SELECT 1 FROM _migrations WHERE version = ?",
            &[version.into()],
        )?;

        Ok(row.is_some())
    }

    /// 执行单个迁移
    fn apply_migration(&self, migration: &Migration) -> Result<(), SqliteError> {
        // 执行迁移 SQL
        self.conn
            .execute_batch(&migration.sql)
            .map_err(|e| SqliteError::MigrationFailed(format!("v{}: {}", migration.version, e)))?;

        // 记录迁移
        self.conn.execute(
            "INSERT INTO _migrations (version, description) VALUES (?, ?)",
            &[migration.version.into(), migration.description.clone().into()],
        )?;

        Ok(())
    }

    /// 执行所有待执行的迁移
    pub fn migrate(&self, migrations: &[Migration]) -> Result<MigrationReport, SqliteError> {
        self.ensure_migration_table()?;

        let mut report = MigrationReport::default();

        // 按版本排序
        let mut sorted: Vec<_> = migrations.iter().collect();
        sorted.sort_by_key(|m| m.version);

        for migration in sorted {
            if self.is_applied(migration.version)? {
                report.skipped += 1;
            } else {
                self.apply_migration(migration)?;
                report.applied += 1;
            }
        }

        report.current_version = self.current_version()?;

        Ok(report)
    }

    /// 使用构建器执行迁移
    pub fn migrate_with<F>(&self, f: F) -> Result<MigrationReport, SqliteError>
    where
        F: FnOnce(&mut MigrationBuilder),
    {
        let mut builder = MigrationBuilder::new();
        f(&mut builder);
        self.migrate(&builder.build())
    }
}

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

    #[test]
    fn test_table_builder() {
        let sql = TableBuilder::new("users")
            .id()
            .text_not_null("name")
            .integer("age")
            .timestamps()
            .build();

        assert!(sql.contains("CREATE TABLE"));
        assert!(sql.contains("id INTEGER PRIMARY KEY"));
        assert!(sql.contains("name TEXT NOT NULL"));
        assert!(sql.contains("created_at"));
    }

    #[test]
    fn test_migration() {
        let conn = Connection::open_in_memory().unwrap();
        let migrator = Migrator::new(&conn);

        let report = migrator
            .migrate_with(|m| {
                m.version(1, "创建用户表", |s| {
                    s.create_table("users", |t| t.id().text_not_null("name").timestamps())
                });
                m.version(2, "添加索引", |s| s.create_index("idx_users_name", "users", &["name"]));
            })
            .unwrap();

        assert_eq!(report.applied, 2);
        assert_eq!(report.current_version, 2);

        // 再次执行应该跳过
        let report2 = migrator
            .migrate_with(|m| {
                m.version(1, "创建用户表", |s| {
                    s.create_table("users", |t| t.id().text_not_null("name").timestamps())
                });
            })
            .unwrap();

        assert_eq!(report2.applied, 0);
        assert_eq!(report2.skipped, 1);
    }

    #[test]
    fn test_schema_builder() {
        let mut schema = SchemaBuilder::new();
        schema
            .create_table("posts", |t| {
                t.id()
                    .text_not_null("title")
                    .text("content")
                    .integer_not_null("user_id")
                    .foreign_key("user_id", "users", "id")
            })
            .unwrap();

        schema
            .create_index("idx_posts_user", "posts", &["user_id"])
            .unwrap();

        let sql = schema.build();
        assert!(sql.contains("CREATE TABLE"));
        assert!(sql.contains("FOREIGN KEY"));
        assert!(sql.contains("CREATE INDEX"));
    }
}