Skip to main content

erdify_rs/
lib.rs

1//! Generates Mermaid ER diagrams from a PostgreSQL database.
2
3pub mod config;
4pub mod db;
5pub mod errors;
6pub mod mermaid;
7pub mod schema;
8
9use crate::config::Args;
10use crate::errors::ErdifyError;
11use std::io::Write as _;
12
13/// Application entry point.
14///
15/// # Errors
16///
17/// Returns an [ErdifyError] if the url is invalid, if the connection or a
18/// query fails, if no table matches the filters, or if writing the output
19/// file fails.
20pub async fn run(args: Args) -> Result<(), ErdifyError> {
21    let url_info = args.parse_url()?;
22
23    let schema_filters = args.parse_csv(args.schema.as_deref());
24    let table_filters = args.parse_csv(args.table.as_deref());
25    let ignore_tables = args.parse_csv(args.ignore_tables.as_deref());
26    let mode = args.output_mode();
27
28    let client = db::connect(&url_info).await?;
29    let tables = db::fetch_tables(&client, &schema_filters, &table_filters, &ignore_tables).await?;
30
31    if tables.is_empty() {
32        return Err(ErdifyError::NoTablesFound);
33    }
34
35    let output = mermaid::render_all(&tables, mode, &args, &url_info.database);
36
37    if let Some(path) = &args.output {
38        tokio::fs::write(path, output).await?;
39    } else {
40        // `output` already ends with a newline: `print!` avoids the extra
41        // blank line that `println!` would add.
42        let mut stdout = std::io::stdout().lock();
43        stdout.write_all(output.as_bytes())?;
44        stdout.flush()?;
45    }
46
47    Ok(())
48}