unistore_sqlite/lib.rs
1//! # unistore-sqlite: SQLite 嵌入式数据库能力
2//!
3//! 为用户提供轻量级嵌入式数据库能力,适用于中小型应用。
4//!
5//! ## 设计哲学
6//!
7//! - **配置权交付**:提供 SQLite 能力而非强制使用
8//! - **零配置启动**:合理的默认配置,开箱即用
9//! - **类型安全**:Rust 类型系统保护,减少运行时错误
10//!
11//! ## 快速开始
12//!
13//! ```ignore
14//! use unistore_sqlite::EmbeddedDb;
15//!
16//! // 创建应用数据库
17//! let db = EmbeddedDb::open("my_inventory")?;
18//!
19//! // 定义表结构
20//! db.migrate(|m| {
21//! m.version(1, "初始化库存表", |s| {
22//! s.create_table("items", |t| {
23//! t.id()
24//! .text_not_null("name")
25//! .integer_not_null("quantity")
26//! .real("price")
27//! .created_at();
28//! })?;
29//! Ok(())
30//! });
31//! })?;
32//!
33//! // 插入数据
34//! let item_id = db.insert("items")
35//! .set("name", "笔记本电脑")
36//! .set("quantity", 10)
37//! .set("price", 5999.0)
38//! .execute()?;
39//!
40//! // 查询数据
41//! let items = db.select("items")
42//! .filter("quantity > ?", 0)
43//! .order_desc("created_at")
44//! .fetch_all()?;
45//! ```
46
47// ============================================================================
48// 内部模块
49// ============================================================================
50
51mod config;
52mod connection;
53mod db;
54mod error;
55mod migration;
56mod query;
57mod transaction;
58mod types;
59
60// ============================================================================
61// 公开 API
62// ============================================================================
63
64// 核心类型
65pub use db::EmbeddedDb;
66pub use error::SqliteError;
67
68// 配置
69pub use config::{SqliteConfig, SynchronousMode};
70
71// 类型系统
72pub use types::{Param, Row, Rows, SqlValue};
73
74// 查询构建器
75pub use query::{DeleteBuilder, InsertBuilder, SelectBuilder, UpdateBuilder};
76
77// 迁移
78pub use migration::{
79 Migration, MigrationBuilder, MigrationReport, SchemaBuilder, TableBuilder, Migrator,
80};
81
82// 事务
83pub use transaction::{
84 IsolationLevel, Transaction, TransactionState,
85 with_transaction, with_immediate_transaction,
86};
87
88// 连接状态
89pub use connection::ConnectionState;
90
91// ============================================================================
92// Capability 实现
93// ============================================================================
94
95use async_trait::async_trait;
96use unistore_core::{Capability, CapabilityError, CapabilityInfo};
97
98/// SQLite 嵌入式数据库能力
99///
100/// 实现 `Capability` trait,可被 UniStore 运行时管理
101pub struct SqliteCapability {
102 db: Option<EmbeddedDb>,
103 config: SqliteConfig,
104}
105
106impl SqliteCapability {
107 /// 创建 SQLite 能力实例(内存数据库)
108 pub fn memory() -> Self {
109 Self {
110 db: None,
111 config: SqliteConfig::memory(),
112 }
113 }
114
115 /// 创建 SQLite 能力实例(文件数据库)
116 pub fn file(path: impl Into<std::path::PathBuf>) -> Self {
117 Self {
118 db: None,
119 config: SqliteConfig::file(path),
120 }
121 }
122
123 /// 使用自定义配置创建
124 pub fn with_config(config: SqliteConfig) -> Self {
125 Self {
126 db: None,
127 config,
128 }
129 }
130
131 /// 获取数据库(能力必须已启动)
132 pub fn db(&self) -> Option<&EmbeddedDb> {
133 self.db.as_ref()
134 }
135}
136
137#[async_trait]
138impl Capability for SqliteCapability {
139 fn info(&self) -> CapabilityInfo {
140 CapabilityInfo::new("sqlite", env!("CARGO_PKG_VERSION"))
141 .with_description("SQLite embedded database capability")
142 .with_author("UniStore Team")
143 }
144
145 async fn start(&mut self) -> Result<(), CapabilityError> {
146 if self.db.is_some() {
147 return Ok(()); // 已启动
148 }
149
150 let db = EmbeddedDb::open_with_config("unistore", self.config.clone())
151 .map_err(|e: SqliteError| CapabilityError::start_failed("sqlite", e.to_string()))?;
152 self.db = Some(db);
153 Ok(())
154 }
155
156 async fn stop(&mut self) -> Result<(), CapabilityError> {
157 self.db = None;
158 Ok(())
159 }
160
161 async fn health_check(&self) -> Result<(), CapabilityError> {
162 match &self.db {
163 Some(db) => {
164 // 执行简单查询验证连接
165 db.execute("SELECT 1", &[])
166 .map_err(|e: SqliteError| CapabilityError::unhealthy("sqlite", e.to_string()))?;
167 Ok(())
168 }
169 None => Err(CapabilityError::unhealthy("sqlite", "数据库未初始化")),
170 }
171 }
172}
173
174// ============================================================================
175// 便捷宏
176// ============================================================================
177
178/// 参数列表构建宏
179///
180/// # 示例
181/// ```ignore
182/// use unistore_sqlite::params;
183/// let params = params![1, "hello", 3.14];
184/// ```
185#[macro_export]
186macro_rules! params {
187 () => {
188 vec![]
189 };
190 ($($param:expr),+ $(,)?) => {
191 vec![$($crate::Param::from($param)),+]
192 };
193}