Skip to main content

sql_splitter/generate/
value.rs

1//! Typed representation of a single generated value.
2//!
3//! Generators produce [`GeneratedValue`] rather than writing SQL literals
4//! directly, so downstream stages (formatting, redaction interop, planner
5//! arithmetic) can inspect and combine values without re-parsing text. Money
6//! and other fixed-point quantities are represented as integer minor units
7//! (e.g. cents) plus a scale, so planner arithmetic never touches floats.
8
9use std::fmt;
10
11use crate::diagnostic::{Diagnostic, DiagnosticBag, DiagnosticDefinition};
12use crate::synthetic::schema::SqlTypeFamily;
13
14/// A single value produced by a generator, independent of any target SQL
15/// dialect's literal syntax.
16#[derive(Debug, Clone, PartialEq)]
17pub enum GeneratedValue {
18    /// SQL `NULL`.
19    Null,
20    /// The column's `DEFAULT` expression, left for the writer to emit.
21    Default,
22    Boolean(bool),
23    /// Any whole-number value, wide enough for `BIGINT` and beyond.
24    Integer(i128),
25    /// A fixed-point number as integer minor units (e.g. cents) plus scale,
26    /// e.g. `{ minor: 1050, scale: 2 }` for `10.50`.
27    Decimal {
28        minor: i128,
29        scale: u32,
30    },
31    Text(String),
32    Bytes(Vec<u8>),
33    /// A pre-formatted date/time/timestamp literal.
34    DateTime(String),
35    /// A pre-serialized JSON document.
36    Json(String),
37}
38
39impl GeneratedValue {
40    /// Whether this value represents SQL `NULL`.
41    pub fn is_null(&self) -> bool {
42        matches!(self, GeneratedValue::Null)
43    }
44
45    /// Borrow the value as a boolean, or a [`GenerateError::TypeMismatch`]
46    /// if it isn't one.
47    pub fn as_boolean(&self) -> Result<bool, GenerateError> {
48        match self {
49            GeneratedValue::Boolean(b) => Ok(*b),
50            other => Err(GenerateError::type_mismatch("Boolean", other)),
51        }
52    }
53
54    /// Borrow the value as an integer, or a [`GenerateError::TypeMismatch`]
55    /// if it isn't one.
56    pub fn as_integer(&self) -> Result<i128, GenerateError> {
57        match self {
58            GeneratedValue::Integer(i) => Ok(*i),
59            other => Err(GenerateError::type_mismatch("Integer", other)),
60        }
61    }
62
63    /// Borrow the value as `(minor units, scale)`, or a
64    /// [`GenerateError::TypeMismatch`] if it isn't a decimal.
65    pub fn as_decimal(&self) -> Result<(i128, u32), GenerateError> {
66        match self {
67            GeneratedValue::Decimal { minor, scale } => Ok((*minor, *scale)),
68            other => Err(GenerateError::type_mismatch("Decimal", other)),
69        }
70    }
71
72    /// Borrow the value as text, or a [`GenerateError::TypeMismatch`] if it
73    /// isn't one.
74    pub fn as_text(&self) -> Result<&str, GenerateError> {
75        match self {
76            GeneratedValue::Text(s) => Ok(s.as_str()),
77            other => Err(GenerateError::type_mismatch("Text", other)),
78        }
79    }
80
81    /// Borrow the value as bytes, or a [`GenerateError::TypeMismatch`] if it
82    /// isn't one.
83    pub fn as_bytes(&self) -> Result<&[u8], GenerateError> {
84        match self {
85            GeneratedValue::Bytes(b) => Ok(b.as_slice()),
86            other => Err(GenerateError::type_mismatch("Bytes", other)),
87        }
88    }
89
90    /// Borrow the value as a pre-formatted date/time literal, or a
91    /// [`GenerateError::TypeMismatch`] if it isn't one.
92    pub fn as_date_time(&self) -> Result<&str, GenerateError> {
93        match self {
94            GeneratedValue::DateTime(s) => Ok(s.as_str()),
95            other => Err(GenerateError::type_mismatch("DateTime", other)),
96        }
97    }
98
99    /// Borrow the value as a pre-serialized JSON document, or a
100    /// [`GenerateError::TypeMismatch`] if it isn't one.
101    pub fn as_json(&self) -> Result<&str, GenerateError> {
102        match self {
103            GeneratedValue::Json(s) => Ok(s.as_str()),
104            other => Err(GenerateError::type_mismatch("Json", other)),
105        }
106    }
107
108    /// Whether this value is a legal payload for a column of `family`,
109    /// independent of any particular generator. `Null` and `Default` are
110    /// legal for every family; every other variant is checked against the
111    /// one or two families it can represent (e.g. a `Uuid`-family column is
112    /// represented as `Text`, since [`GeneratedValue`] has no dedicated
113    /// UUID variant).
114    pub fn compatible_with(&self, family: &SqlTypeFamily) -> bool {
115        match self {
116            GeneratedValue::Null | GeneratedValue::Default => true,
117            GeneratedValue::Boolean(_) => matches!(family, SqlTypeFamily::Boolean),
118            GeneratedValue::Integer(_) => {
119                matches!(family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
120            }
121            GeneratedValue::Decimal { .. } => matches!(family, SqlTypeFamily::Decimal),
122            GeneratedValue::Text(_) => matches!(
123                family,
124                SqlTypeFamily::Text | SqlTypeFamily::Uuid | SqlTypeFamily::Other
125            ),
126            GeneratedValue::Bytes(_) => matches!(family, SqlTypeFamily::Bytes),
127            GeneratedValue::DateTime(_) => matches!(family, SqlTypeFamily::DateTime),
128            GeneratedValue::Json(_) => matches!(family, SqlTypeFamily::Json),
129        }
130    }
131
132    /// The name of this value's variant, for error messages built outside
133    /// this module (e.g. a modifier reporting a type mismatch it detected
134    /// itself, rather than through one of the `as_*` accessors above).
135    pub fn type_name(&self) -> &'static str {
136        self.kind_name()
137    }
138
139    /// The name of this value's variant, used in error messages.
140    fn kind_name(&self) -> &'static str {
141        match self {
142            GeneratedValue::Null => "Null",
143            GeneratedValue::Default => "Default",
144            GeneratedValue::Boolean(_) => "Boolean",
145            GeneratedValue::Integer(_) => "Integer",
146            GeneratedValue::Decimal { .. } => "Decimal",
147            GeneratedValue::Text(_) => "Text",
148            GeneratedValue::Bytes(_) => "Bytes",
149            GeneratedValue::DateTime(_) => "DateTime",
150            GeneratedValue::Json(_) => "Json",
151        }
152    }
153}
154
155/// Errors returned while running a compiled generator or modifier.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub enum GenerateError {
158    /// A typed accessor was called on a value of a different variant.
159    TypeMismatch {
160        expected: &'static str,
161        found: &'static str,
162    },
163    /// A generator's internal state (e.g. a `sequence`'s counter) could not
164    /// advance without wrapping past its representable range.
165    Overflow(String),
166    /// A modifier (e.g. `unique`) could not satisfy its constraint within
167    /// its configured attempt budget.
168    Exhausted(String),
169    /// A generator could not make sense of a value it depends on at row
170    /// time (e.g. `before`/`after` reading an unparsable source column).
171    InvalidInput(String),
172    /// Structured diagnostics from loading, merging, or compiling a model,
173    /// surfaced through the public [`crate::generate::Generate`] API (e.g.
174    /// `ModelCompiler::compile` errors, or `ModelMerger::merge` errors).
175    /// Carries the full bag, including any warnings, so a caller can report
176    /// every problem rather than just the first.
177    Diagnostics(DiagnosticBag),
178    /// One structured runtime diagnostic. Unlike [`Self::Diagnostics`], this
179    /// variant represents a single failure discovered after compilation.
180    Diagnostic(Box<Diagnostic>),
181}
182
183impl GenerateError {
184    fn type_mismatch(expected: &'static str, found: &GeneratedValue) -> Self {
185        GenerateError::TypeMismatch {
186            expected,
187            found: found.kind_name(),
188        }
189    }
190
191    /// Construct a structured built-in runtime failure.
192    pub fn diagnostic(
193        definition: &'static DiagnosticDefinition,
194        path: impl Into<String>,
195        message: impl Into<String>,
196    ) -> Self {
197        GenerateError::Diagnostic(Box::new(Diagnostic::error(definition, path, message)))
198    }
199}
200
201impl fmt::Display for GenerateError {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        match self {
204            GenerateError::TypeMismatch { expected, found } => {
205                write!(f, "expected a {expected} value, found {found}")
206            }
207            GenerateError::Overflow(message) => write!(f, "{message}"),
208            GenerateError::Exhausted(message) => write!(f, "{message}"),
209            GenerateError::InvalidInput(message) => write!(f, "{message}"),
210            GenerateError::Diagnostics(bag) => write!(f, "{bag}"),
211            GenerateError::Diagnostic(diagnostic) => write!(f, "{diagnostic}"),
212        }
213    }
214}
215
216impl std::error::Error for GenerateError {}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn accessors_return_the_matching_variant() {
224        assert_eq!(GeneratedValue::Boolean(true).as_boolean(), Ok(true));
225        assert_eq!(GeneratedValue::Integer(7).as_integer(), Ok(7));
226        assert_eq!(
227            GeneratedValue::Decimal {
228                minor: 1050,
229                scale: 2
230            }
231            .as_decimal(),
232            Ok((1050, 2))
233        );
234        assert_eq!(GeneratedValue::Text("hi".into()).as_text(), Ok("hi"));
235        assert_eq!(
236            GeneratedValue::Bytes(vec![1, 2, 3]).as_bytes(),
237            Ok([1u8, 2, 3].as_slice())
238        );
239        assert_eq!(
240            GeneratedValue::DateTime("2024-01-01".into()).as_date_time(),
241            Ok("2024-01-01")
242        );
243        assert_eq!(GeneratedValue::Json("{}".into()).as_json(), Ok("{}"));
244    }
245
246    #[test]
247    fn accessors_return_type_mismatch_instead_of_panicking() {
248        let value = GeneratedValue::Null;
249        assert_eq!(
250            value.as_integer(),
251            Err(GenerateError::TypeMismatch {
252                expected: "Integer",
253                found: "Null",
254            })
255        );
256    }
257
258    #[test]
259    fn is_null_reports_only_the_null_variant() {
260        assert!(GeneratedValue::Null.is_null());
261        assert!(!GeneratedValue::Default.is_null());
262        assert!(!GeneratedValue::Integer(0).is_null());
263    }
264
265    #[test]
266    fn compatible_with_accepts_null_and_default_for_every_family() {
267        assert!(GeneratedValue::Null.compatible_with(&SqlTypeFamily::Integer));
268        assert!(GeneratedValue::Default.compatible_with(&SqlTypeFamily::Json));
269    }
270
271    #[test]
272    fn compatible_with_matches_variant_to_family() {
273        assert!(GeneratedValue::Integer(1).compatible_with(&SqlTypeFamily::BigInteger));
274        assert!(!GeneratedValue::Integer(1).compatible_with(&SqlTypeFamily::Text));
275        assert!(GeneratedValue::Text("id".into()).compatible_with(&SqlTypeFamily::Uuid));
276        assert!(!GeneratedValue::Json("{}".into()).compatible_with(&SqlTypeFamily::Text));
277    }
278}