# unistore-sqlite
UniStore SQLite 嵌入式数据库能力,提供类型安全的数据库操作。
## 概述
`unistore-sqlite` 提供:
- 零配置启动,开箱即用
- 类型安全的查询构建器
- Schema 迁移支持
- 事务支持(RAII 自动回滚)
- 与 UniStore 生命周期集成
## 安装
```toml
[dependencies]
unistore-sqlite = "0.1"
```
## 快速开始
```rust
use unistore_sqlite::EmbeddedDb;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 打开或创建数据库
let db = EmbeddedDb::open("my_app")?;
// 定义表结构
db.migrate(|m| {
m.version(1, "创建用户表", |s| {
s.create_table("users", |t| {
t.id()
.text_not_null("name")
.text("email")
.created_at();
})
});
})?;
// 插入数据
let id = db.insert("users")
.set("name", "Alice")
.set("email", "alice@example.com")
.execute()?;
// 查询数据
let users = db.select("users")
.filter("id = ?", id)
.fetch_all()?;
// 更新数据
db.update("users")
.set("name", "Alice Smith")
.filter("id = ?", id)
.execute()?;
// 删除数据
db.delete("users")
.filter("id = ?", id)
.execute()?;
Ok(())
}
```
## 事务
```rust
db.with_transaction(|tx| {
tx.execute("INSERT INTO users (name) VALUES (?)", &["Bob"])?;
tx.execute("INSERT INTO logs (action) VALUES (?)", &["created user"])?;
Ok(())
})?;
// 自动提交,出错自动回滚
```
## 配置预设
```rust
// 内存数据库(测试用)
let db = EmbeddedDb::memory()?;
// 性能优先
let config = SqliteConfig::performance();
// 持久性优先
let config = SqliteConfig::durable();
```
## 底层访问
需要直接使用 rusqlite 时:
```rust
db.with_connection(|conn| {
// conn 是 &rusqlite::Connection
conn.execute("PRAGMA optimize", [])?;
Ok(())
})?;
```
## 许可证
MIT OR Apache-2.0
## 致谢
本 crate 基于以下优秀项目构建:
- [rusqlite](https://github.com/rusqlite/rusqlite) - Rust 的 SQLite 绑定
- [SQLite](https://sqlite.org/) - 世界上使用最广泛的数据库引擎
感谢 rusqlite 团队和 SQLite 团队的杰出工作!