rp_supabase_codegen/
lib.rs1extern crate alloc;
7
8#[cfg(feature = "database")]
9mod database;
10mod emitter;
11pub mod model;
12
13use alloc::collections::BTreeMap;
14use std::path::{Path, PathBuf};
15
16use model::{SNAPSHOT_VERSION, Snapshot};
17
18#[expect(
20 clippy::error_impl_error,
21 reason = "The module-qualified codegen::Error is unambiguous for callers."
22)]
23#[derive(Debug, thiserror::Error)]
24pub enum Error {
25 #[error("invalid schema generation input: {0}")]
26 Invalid(String),
27 #[error("schema generation I/O failed: {0}")]
28 Io(#[from] std::io::Error),
29 #[error("invalid schema snapshot: {0}")]
30 Json(#[from] serde_json::Error),
31 #[error("PostgreSQL schema introspection failed: {0}")]
32 Database(String),
33}
34
35#[derive(Debug, Clone)]
36struct Config {
37 pub schemas: Vec<String>,
38 pub prelude: String,
39 pub derives: Vec<String>,
40 pub attributes: Vec<String>,
41 pub type_overrides: BTreeMap<String, String>,
42 pub type_attributes: BTreeMap<String, Vec<String>>,
43 pub runtime_path: String,
44}
45
46#[derive(Debug, Clone)]
51pub struct Generator {
52 config: Config,
53}
54
55impl Default for Generator {
56 fn default() -> Self {
57 Self::new()
58 }
59}
60
61#[expect(
62 clippy::impl_trait_in_params,
63 reason = "Consuming configuration methods accept owned strings and borrowed literals without named generic parameters."
64)]
65#[expect(
66 clippy::wrong_self_convention,
67 reason = "Each from_* method consumes configured generation options and selects an input adapter."
68)]
69impl Generator {
70 #[must_use]
71 pub fn new() -> Self {
72 Self {
73 config: Config {
74 schemas: vec!["public".to_owned()],
75 prelude: String::new(),
76 derives: Vec::new(),
77 attributes: Vec::new(),
78 type_overrides: BTreeMap::new(),
79 type_attributes: BTreeMap::new(),
80 runtime_path: "::rp_supabase_client::schema".to_owned(),
81 },
82 }
83 }
84
85 #[must_use]
87 pub fn schemas(mut self, schemas: impl IntoIterator<Item = impl Into<String>>) -> Self {
88 self.config.schemas = schemas.into_iter().map(Into::into).collect();
89 self
90 }
91
92 #[must_use]
94 pub fn schema(self, schema: impl Into<String>) -> Self {
95 self.schemas([schema.into()])
96 }
97
98 #[must_use]
100 pub fn prelude(mut self, prelude: impl Into<String>) -> Self {
101 self.config.prelude = prelude.into();
102 self
103 }
104
105 #[must_use]
107 pub fn derive(mut self, derive: impl Into<String>) -> Self {
108 self.config.derives.push(derive.into());
109 self
110 }
111
112 #[must_use]
114 pub fn attribute(mut self, attribute: impl Into<String>) -> Self {
115 self.config.attributes.push(attribute.into());
116 self
117 }
118
119 #[must_use]
124 pub fn type_attribute(
125 mut self,
126 generated_type: impl Into<String>,
127 attribute: impl Into<String>,
128 ) -> Self {
129 self.config
130 .type_attributes
131 .entry(generated_type.into())
132 .or_default()
133 .push(attribute.into());
134 self
135 }
136
137 #[must_use]
139 pub fn type_override(
140 mut self,
141 postgres_type: impl Into<String>,
142 rust_type: impl Into<String>,
143 ) -> Self {
144 self.config
145 .type_overrides
146 .insert(postgres_type.into(), rust_type.into());
147 self
148 }
149
150 #[must_use]
152 pub fn runtime_path(mut self, path: impl Into<String>) -> Self {
153 self.config.runtime_path = path.into();
154 self
155 }
156
157 #[expect(
162 clippy::print_stdout,
163 reason = "Cargo build scripts receive change instructions on stdout."
164 )]
165 pub fn from_snapshot(self, path: impl AsRef<Path>) -> Result<Bindings, Error> {
166 let path = path.as_ref();
167 cargo_path(path)?;
168 println!("cargo::rerun-if-changed={}", path.display());
169 let snapshot = serde_json::from_slice(&std::fs::read(path)?)?;
170 self.from_metadata(snapshot)
171 }
172
173 pub fn from_metadata(self, snapshot: Snapshot) -> Result<Bindings, Error> {
178 if snapshot.version != SNAPSHOT_VERSION {
179 return Err(Error::Invalid(format!(
180 "snapshot version {} is unsupported; expected {SNAPSHOT_VERSION}",
181 snapshot.version
182 )));
183 }
184 if self.config.schemas.is_empty() || self.config.schemas.iter().any(String::is_empty) {
185 return Err(Error::Invalid(
186 "select at least one nonempty schema".to_owned(),
187 ));
188 }
189 for schema in &self.config.schemas {
190 if !snapshot.schemas.iter().any(|item| &item.name == schema) {
191 return Err(Error::Invalid(format!(
192 "selected schema {schema:?} is absent from the snapshot"
193 )));
194 }
195 }
196 let source = emitter::generate(&snapshot, &self.config)?;
197 Ok(Bindings { snapshot, source })
198 }
199
200 #[cfg(feature = "database")]
208 pub fn from_database(self, url: &str) -> Result<Bindings, Error> {
209 let snapshot = database::introspect(url, &self.config.schemas)?;
210 self.from_metadata(snapshot)
211 }
212
213 #[cfg(feature = "database")]
220 #[expect(
221 clippy::print_stdout,
222 reason = "Cargo build scripts receive change instructions on stdout."
223 )]
224 pub fn from_database_env(self, variable: &str) -> Result<Bindings, Error> {
225 if variable.is_empty() || variable.contains(['\n', '\r', '=']) {
226 return Err(Error::Invalid(
227 "invalid database environment variable name".to_owned(),
228 ));
229 }
230 println!("cargo::rerun-if-env-changed={variable}");
231 let url = std::env::var(variable).map_err(|_error| {
232 Error::Invalid(format!("set {variable} to a PostgreSQL connection string"))
233 })?;
234 self.from_database(&url)
235 }
236}
237
238#[derive(Debug, Clone)]
240pub struct Bindings {
241 snapshot: Snapshot,
242 source: String,
243}
244
245#[expect(
246 clippy::impl_trait_in_params,
247 reason = "Path arguments accept standard owned and borrowed path types."
248)]
249impl Bindings {
250 #[must_use]
251 pub fn source(&self) -> &str {
252 &self.source
253 }
254
255 #[must_use]
256 pub const fn snapshot(&self) -> &Snapshot {
257 &self.snapshot
258 }
259
260 pub fn write_to(&self, path: impl AsRef<Path>) -> Result<(), Error> {
265 write_if_changed(path.as_ref(), self.source.as_bytes())
266 }
267
268 pub fn write_to_out_dir(&self, filename: &str) -> Result<PathBuf, Error> {
273 let path = Path::new(filename);
274 if path.components().count() != 1
275 || !matches!(
276 path.components().next(),
277 Some(std::path::Component::Normal(_))
278 )
279 {
280 return Err(Error::Invalid(
281 "OUT_DIR filename must be one normal path component".to_owned(),
282 ));
283 }
284 let output = std::env::var_os("OUT_DIR").ok_or_else(|| {
285 Error::Invalid("OUT_DIR is absent; call this method from build.rs".to_owned())
286 })?;
287 let output = PathBuf::from(output).join(filename);
288 self.write_to(&output)?;
289 Ok(output)
290 }
291
292 pub fn write_snapshot(&self, path: impl AsRef<Path>) -> Result<(), Error> {
297 let mut bytes = serde_json::to_vec_pretty(&self.snapshot)?;
298 bytes.push(b'\n');
299 write_if_changed(path.as_ref(), &bytes)
300 }
301}
302
303fn cargo_path(path: &Path) -> Result<(), Error> {
304 let Some(path) = path.to_str() else {
305 return Err(Error::Invalid("Cargo input paths must be UTF-8".to_owned()));
306 };
307 if path.contains(['\n', '\r']) {
308 return Err(Error::Invalid(
309 "Cargo input paths cannot contain line breaks".to_owned(),
310 ));
311 }
312 Ok(())
313}
314
315fn write_if_changed(path: &Path, contents: &[u8]) -> Result<(), Error> {
316 match std::fs::read(path) {
317 Ok(existing) if existing == contents => return Ok(()),
318 Ok(_) => {}
319 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
320 Err(error) => return Err(error.into()),
321 }
322 std::fs::write(path, contents)?;
323 Ok(())
324}