Skip to main content

iridium_proto/
lib.rs

1//! Generate Rust models and mappers from a live PostgreSQL schema.
2//!
3//! `iridium-proto` reads the Postgres catalogs and writes the Rust you
4//! would otherwise write by hand: a struct per table, the Rust enums
5//! behind its enum types, and a repository that runs the queries. It is
6//! primarily a command-line tool, `proto`, with the library exposed so the
7//! same work can be done from a build script or a test.
8//!
9//! # The command
10//!
11//! ```text
12//! proto model shop.product --pyo3      # one model, to stdout
13//! proto mapper shop.product            # its repository
14//! proto schema shop --out-dir src/model
15//! proto database --out-dir src/model --mapper-dir src/mapper --mappers
16//! proto schema shop --mappers --operations \
17//!     --out-dir src/model --mapper-dir src/mapper --operation-dir src/operation
18//! proto list [schema]                  # what is there
19//! proto config                         # what proto resolved
20//! ```
21//!
22//! Output goes to stdout unless a destination is given, which is what
23//! makes `:%!proto model shop.product` work from an editor buffer.
24//!
25//! # Generated code you can live in
26//!
27//! A regeneration corrects a file rather than replacing it. Proto
28//! renders what the file should say, parses both that and what is on
29//! disk, and edits only where they disagree — so a field whose type no
30//! longer matches its column is replaced, and the comment a developer
31//! wrote above it stays above it.
32//!
33//! The database is right about the parts it owns: names, types,
34//! nullability. Everything else in the file is yours, including the
35//! order, since fields are matched by name. Mappers work the same way a
36//! method at a time: proto owns the ones it derives from the catalog and
37//! nothing else in the block. Nothing has to be marked to be spared,
38//! because nothing is rewritten. See [`reconcile`].
39//!
40//! # What comes out
41//!
42//! A table becomes a struct. `NOT NULL` columns get a bare type and
43//! everything else gets [`Option`]; column comments become doc comments.
44//!
45//! ```text
46//! #[derive(sqlx::FromRow, Debug, Clone, Serialize, Deserialize)]
47//! pub struct Product {
48//!     pub id: Uuid,
49//!     pub slug: String,
50//!     pub status: ProductStatus,
51//!     pub price: Option<Decimal>,
52//! }
53//! ```
54//!
55//! Its mapper owns the SQL:
56//!
57//! ```text
58//! let products = ProductMapper::new(&pool);
59//! let one = products.find_by_slug("dovetail-saw").await?;
60//! let all = products.find_by_org_id(org).await?;
61//! ```
62//!
63//! # Two places for the SQL
64//!
65//! [`render::Strategy`] decides where the statements live. Under
66//! [`Embedded`](render::Strategy::Embedded) they are in the Rust source.
67//! Under [`Server`](render::Strategy::Server) they are `LANGUAGE sql`
68//! functions in a migration [`render::sql`] writes, and the mapper only
69//! calls them. Both produce the same Rust API, so the choice is about
70//! where the logic should live, not about how the code is used.
71//!
72//! # Using it as a library
73//!
74//! [`introspect`] reads a table, [`render`] turns it into source. Nothing
75//! in [`render`] touches a database, so the emitters are testable on their
76//! own.
77//!
78//! ```no_run
79//! use iridium_proto::config::Generate;
80//! use iridium_proto::{introspect, render};
81//! use sqlx::PgPool;
82//!
83//! # async fn example(pool: &PgPool) -> Result<(), Box<dyn std::error::Error>> {
84//! let model = introspect::model(pool, "shop", "product").await?;
85//!
86//! let generate = Generate::default();
87//! let opts = render::Opts {
88//!     generate: &generate,
89//!     pyo3: false,
90//!     inputs: true,
91//!     model_path: "crate::model".to_string(),
92//!     strategy: render::Strategy::Embedded,
93//!     target: "dev",
94//!     command: "proto model shop.product".to_string(),
95//!     name_override: None,
96//!     bridge_path: "super::python".to_string(),
97//!     query_path: "super::query".to_string(),
98//!     mapper_path: "crate::mapper".to_string(),
99//! };
100//!
101//! print!("{}", render::model::model_file(&model, &opts, None).code);
102//! print!("{}", render::mapper::mapper_file(&model, &opts).code);
103//! # Ok(())
104//! # }
105//! ```
106//!
107//! # Configuration
108//!
109//! Database targets and generation defaults come from a TOML file, read
110//! from `$PROTO_CONFIG`, else `$XDG_CONFIG_HOME/proto/proto.toml`, else
111//! `~/.config/proto/proto.toml`. See [`config`] for the shape of it.
112//!
113//! # Reading on
114//!
115//! The README is the pitch and the workflow; the reference is a page per
116//! subject in the repository's `docs/` directory — configuration and
117//! commands, models, mappers, children, operations, type mapping,
118//! keeping in step, editing generated code, safety, and pyo3:
119//! <https://github.com/iridiumdesign/iridium-proto/tree/main/docs>.
120
121#![warn(missing_docs)]
122#![warn(clippy::doc_markdown)]
123
124pub mod config;
125pub mod error;
126pub mod inspect;
127pub mod introspect;
128pub mod manifest;
129pub mod naming;
130pub mod output;
131pub mod quoting;
132pub mod reconcile;
133pub mod render;
134pub mod typemap;