Skip to main content

sqltrail_cli/
lib.rs

1//! # sqltrail-cli
2//!
3//! 通用的 PostgreSQL 结构迁移库与命令行工具。
4//!
5//! 提供完整迁移流水线:
6//! **连接数据库 → 读取实际结构 → 与期望结构比较 → 生成迁移计划 → 渲染 SQL → 执行并记录历史**。
7//!
8//! ## 作为库使用(可被任意 Rust 项目引用)
9//!
10//! ```rust,ignore
11//! use sqltrail_cli::{plan_from_database, SchemaModel, MigrationPlan};
12//!
13//! #[tokio::main]
14//! async fn main() -> anyhow::Result<()> {
15//!     let client = sqltrail_cli::database::connect("postgres://user:pass@localhost:5432/db").await?;
16//!
17//!     // 期望结构来源一:你的 Rust struct(配合 sqltrail-macros 派生宏)
18//!     let desired: SchemaModel = /* User::schema() 或从 JSON 加载 */ SchemaModel::default();
19//!
20//!     // 期望结构来源二:加载 SchemaModel JSON 文件(可由 inspect 导出)
21//!     // let desired: SchemaModel = serde_json::from_str(&std::fs::read_to_string("desired.json")?)?;
22//!
23//!     let plan: MigrationPlan = plan_from_database(&client, &desired).await?;
24//!     println!("{}", sqltrail_cli::generator::render_plan(&plan));
25//!     Ok(())
26//! }
27//! ```
28//!
29//! ## 作为 CLI 使用
30//!
31//! ```text
32//! sqltrail-cli status
33//! sqltrail-cli inspect
34//! sqltrail-cli plan --desired desired.json
35//! sqltrail-cli generate add_user_avatar --desired desired.json
36//! sqltrail-cli apply [--allow-destructive]
37//! ```
38
39pub mod database;
40pub mod generator;
41pub mod history;
42pub mod introspection;
43
44// 结构模型、差异计算、迁移计划与统一校验全部通过本 crate 再导出,
45// 接入项目只需依赖 sqltrail-cli(或直接依赖 sqltrail-core)。
46pub use sqltrail_core::*;
47
48/// 便捷入口:读取数据库实际结构,与期望结构比较,返回迁移计划。
49///
50/// 等价于 `build_plan(&compute_diff(desired, &introspection::introspect(client).await?))`。
51pub async fn plan_from_database(
52    client: &tokio_postgres::Client,
53    desired: &SchemaModel,
54) -> anyhow::Result<MigrationPlan> {
55    if let Err(errors) = validate(desired) {
56        anyhow::bail!("期望结构校验失败:{}", errors.join(";"));
57    }
58    let actual = introspection::introspect(client).await?;
59    Ok(build_plan(&compute_diff(desired, &actual)))
60}