Skip to main content

waypoint_core/
lib.rs

1//! Lightweight, Flyway-compatible SQL migration library.
2//!
3//! Targets PostgreSQL (default `postgres` feature) and MySQL 8.0+ (opt-in
4//! `mysql` feature). Build with both features for mixed-engine multi-database
5//! configurations.
6//!
7//! # Quick Start
8//!
9//! ```rust,no_run
10//! use waypoint_core::config::{CliOverrides, WaypointConfig};
11//! use waypoint_core::Waypoint;
12//!
13//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
14//! // `None` reads ./waypoint.toml; pass Some(path) for a different file.
15//! let config = WaypointConfig::load(None, &CliOverrides::default())?;
16//! let wp = Waypoint::new(config).await?;
17//! let report = wp.migrate(None).await?;
18//! println!("Applied {} migrations", report.migrations_applied);
19//! # Ok(())
20//! # }
21//! ```
22//!
23//! # Architecture
24//!
25//! - [`config`] — Configuration loading (TOML, env vars, CLI overrides)
26//! - [`dialect`] — Engine-specific dialect (Postgres / MySQL) abstraction
27//! - [`migration`] — Migration file parsing and scanning
28//! - [`db`] — Database connections, TLS, advisory locks
29//! - [`history`] — Schema history table operations
30//! - [`commands`] — Individual command implementations
31//! - [`checksum`] — CRC32 checksums (Flyway-compatible)
32//! - [`placeholder`] — `${key}` placeholder replacement in SQL
33//! - [`hooks`] — SQL callback hooks (before/after migrate)
34//! - [`directive`] — `-- waypoint:*` comment directive parsing
35//! - [`guard`] — Guard expression parser and evaluator for pre/post conditions
36//! - [`sql_parser`] — Regex-based DDL extraction
37//! - [`safety`] — Migration safety analysis (lock levels, impact, verdicts)
38//! - [`schema`] — Schema introspection + diff
39//! - [`dependency`] — Migration dependency graph
40//! - [`preflight`] — Pre-migration health checks
41//! - [`multi`] — Multi-database orchestration
42//! - [`error`] — Error types
43
44pub mod advisor;
45pub mod checksum;
46pub mod commands;
47pub mod config;
48pub mod db;
49pub mod dependency;
50pub mod dialect;
51pub mod directive;
52pub mod engines;
53pub mod error;
54pub mod guard;
55pub mod history;
56pub mod hooks;
57pub mod migration;
58pub mod multi;
59pub mod placeholder;
60pub mod preflight;
61pub mod reversal;
62pub mod safety;
63pub mod schema;
64pub mod sql_parser;
65
66use std::path::PathBuf;
67
68use config::WaypointConfig;
69use db::DbClient;
70use error::Result;
71
72#[cfg(feature = "postgres")]
73use tokio_postgres::Client;
74
75pub use advisor::AdvisorReport;
76pub use commands::changelog::ChangelogReport;
77pub use commands::check_conflicts::ConflictReport;
78pub use commands::diff::DiffReport;
79pub use commands::drift::DriftReport;
80pub use commands::explain::ExplainReport;
81pub use commands::info::{MigrationInfo, MigrationState};
82pub use commands::lint::LintReport;
83pub use commands::migrate::MigrateReport;
84pub use commands::repair::RepairReport;
85pub use commands::safety::SafetyCommandReport;
86pub use commands::simulate::SimulationReport;
87pub use commands::snapshot::{RestoreReport, SnapshotReport};
88pub use commands::undo::{UndoReport, UndoTarget};
89pub use commands::validate::ValidateReport;
90pub use config::CliOverrides;
91pub use dialect::{DatabaseDialect, DialectKind};
92pub use multi::MultiWaypoint;
93pub use preflight::PreflightReport;
94pub use safety::SafetyReport;
95
96/// Main entry point for the Waypoint library.
97///
98/// Create a `Waypoint` instance with a config and use its methods to
99/// run migration commands programmatically.
100pub struct Waypoint {
101    pub config: WaypointConfig,
102    client: DbClient,
103}
104
105impl Waypoint {
106    /// Create a new Waypoint instance, connecting to the database.
107    ///
108    /// Engine is auto-detected from the configured connection URL scheme
109    /// (`postgres://` / `postgresql://` → PostgreSQL, `mysql://` → MySQL).
110    /// If `connect_retries` is configured, retries with exponential backoff.
111    pub async fn new(config: WaypointConfig) -> Result<Self> {
112        let conn_string = config.connection_string()?;
113        let client = db::connect_for_url(&conn_string, &config).await?;
114        Ok(Self { config, client })
115    }
116
117    /// Create a new Waypoint instance with an existing PostgreSQL client.
118    ///
119    /// Convenience constructor preserved for backwards compatibility. For new
120    /// code or for MySQL connections, use [`Self::with_db_client`].
121    #[cfg(feature = "postgres")]
122    pub fn with_client(config: WaypointConfig, client: Client) -> Self {
123        Self {
124            config,
125            client: DbClient::with_postgres(client),
126        }
127    }
128
129    /// Create a new Waypoint instance with an already-constructed [`DbClient`].
130    pub fn with_db_client(config: WaypointConfig, client: DbClient) -> Self {
131        Self { config, client }
132    }
133
134    /// Get a reference to the underlying database client.
135    pub fn client(&self) -> &DbClient {
136        &self.client
137    }
138
139    /// Get a reference to the underlying PostgreSQL client.
140    ///
141    /// Returns an error if this `Waypoint` was constructed for a non-PostgreSQL
142    /// engine. Most legacy callers can keep using this; new code should prefer
143    /// [`Self::client`] which returns a backend-agnostic [`DbClient`].
144    #[cfg(feature = "postgres")]
145    pub fn postgres_client(&self) -> Result<&Client> {
146        self.client.as_postgres()
147    }
148
149    /// Apply pending migrations.
150    pub async fn migrate(&self, target_version: Option<&str>) -> Result<MigrateReport> {
151        self.migrate_with_options(target_version, false).await
152    }
153
154    /// Apply pending migrations with the additional `force` flag for
155    /// overriding DANGER safety verdicts (PostgreSQL only; MySQL safety
156    /// analysis does not currently gate migrations).
157    pub async fn migrate_with_options(
158        &self,
159        target_version: Option<&str>,
160        force: bool,
161    ) -> Result<MigrateReport> {
162        match self.client.dialect_kind() {
163            #[cfg(feature = "postgres")]
164            DialectKind::Postgres => {
165                commands::migrate::execute_with_options(
166                    self.client.as_postgres()?,
167                    &self.config,
168                    target_version,
169                    force,
170                )
171                .await
172            }
173            #[cfg(not(feature = "postgres"))]
174            DialectKind::Postgres => Err(error::WaypointError::ConfigError(
175                "PostgreSQL support is not compiled in (enable the `postgres` feature)".into(),
176            )),
177            #[cfg(feature = "mysql")]
178            DialectKind::Mysql => {
179                commands::migrate::execute_mysql_with_options(
180                    &self.client,
181                    &self.config,
182                    target_version,
183                    force,
184                )
185                .await
186            }
187            #[cfg(not(feature = "mysql"))]
188            DialectKind::Mysql => Err(error::WaypointError::ConfigError(
189                "MySQL support is not compiled in (enable the `mysql` feature)".into(),
190            )),
191        }
192    }
193
194    /// Show migration status information.
195    pub async fn info(&self) -> Result<Vec<MigrationInfo>> {
196        commands::info::execute_db(&self.client, &self.config).await
197    }
198
199    /// Validate applied migrations against local files.
200    pub async fn validate(&self) -> Result<ValidateReport> {
201        commands::validate::execute_db(&self.client, &self.config).await
202    }
203
204    /// Repair the schema history table.
205    pub async fn repair(&self) -> Result<RepairReport> {
206        commands::repair::execute_db(&self.client, &self.config).await
207    }
208
209    /// Baseline an existing database.
210    pub async fn baseline(&self, version: Option<&str>, description: Option<&str>) -> Result<()> {
211        commands::baseline::execute_db(&self.client, &self.config, version, description).await
212    }
213
214    /// Undo applied migrations.
215    pub async fn undo(&self, target: UndoTarget) -> Result<UndoReport> {
216        commands::undo::execute_db(&self.client, &self.config, target).await
217    }
218
219    /// Drop all objects in managed schemas.
220    pub async fn clean(&self, allow_clean: bool) -> Result<Vec<String>> {
221        commands::clean::execute_db(&self.client, &self.config, allow_clean).await
222    }
223
224    /// Run lint on migration files (no DB required).
225    pub fn lint(locations: &[PathBuf], disabled_rules: &[String]) -> Result<LintReport> {
226        commands::lint::execute(locations, disabled_rules)
227    }
228
229    /// Generate changelog from migration files (no DB required).
230    pub fn changelog(
231        locations: &[PathBuf],
232        from: Option<&str>,
233        to: Option<&str>,
234    ) -> Result<ChangelogReport> {
235        commands::changelog::execute(locations, from, to)
236    }
237
238    /// Compare database schema against a target.
239    pub async fn diff(&self, target: commands::diff::DiffTarget) -> Result<DiffReport> {
240        commands::diff::execute_db(&self.client, &self.config, target).await
241    }
242
243    /// Detect schema drift.
244    pub async fn drift(&self) -> Result<DriftReport> {
245        commands::drift::execute_db(&self.client, &self.config).await
246    }
247
248    /// Take a schema snapshot.
249    pub async fn snapshot(
250        &self,
251        snapshot_config: &commands::snapshot::SnapshotConfig,
252    ) -> Result<SnapshotReport> {
253        commands::snapshot::execute_snapshot_db(&self.client, &self.config, snapshot_config).await
254    }
255
256    /// Restore from a schema snapshot.
257    pub async fn restore(
258        &self,
259        snapshot_config: &commands::snapshot::SnapshotConfig,
260        snapshot_id: &str,
261    ) -> Result<RestoreReport> {
262        commands::snapshot::execute_restore_db(
263            &self.client,
264            &self.config,
265            snapshot_config,
266            snapshot_id,
267        )
268        .await
269    }
270
271    /// Run enhanced dry-run with EXPLAIN.
272    pub async fn explain(&self) -> Result<ExplainReport> {
273        commands::explain::execute_db(&self.client, &self.config).await
274    }
275
276    /// Run pre-flight health checks.
277    pub async fn preflight(&self) -> Result<PreflightReport> {
278        preflight::run_preflight_db(&self.client, &self.config.preflight).await
279    }
280
281    /// Check for branch conflicts (no DB required).
282    pub fn check_conflicts(locations: &[PathBuf], base_branch: &str) -> Result<ConflictReport> {
283        commands::check_conflicts::execute(locations, base_branch)
284    }
285
286    /// Analyze pending migrations for safety (lock analysis, impact estimation).
287    pub async fn safety(&self) -> Result<SafetyCommandReport> {
288        commands::safety::execute_db(&self.client, &self.config).await
289    }
290
291    /// Run schema advisor to suggest improvements.
292    pub async fn advise(&self) -> Result<AdvisorReport> {
293        commands::advisor::execute_db(&self.client, &self.config).await
294    }
295
296    /// Simulate pending migrations in a throwaway schema.
297    pub async fn simulate(&self) -> Result<SimulationReport> {
298        commands::simulate::execute_db(&self.client, &self.config).await
299    }
300}