Skip to main content

sql_values/postgres/
value.rs

1//! A known PostgreSQL value of one of the types whose comparisons need no setting, compared as
2//! PostgreSQL 18's comparison operators compare it, across types where it has an operator between
3//! them.
4
5use alloc::string::String;
6use core::{
7    cmp::Ordering,
8    fmt,
9    hash::{Hash, Hasher},
10};
11
12use super::{
13    array::PgArray,
14    bpchar::PgBpchar,
15    cast::{CastError, CastValue},
16    datetime::{PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz},
17    integer::IntegerType,
18    interval::PgInterval,
19    jsonb::PgJsonb,
20    numeric::PgNumeric,
21    uuid::PgUuid,
22};
23
24/// A known PostgreSQL value, equal, ordered and hashed by its type's comparison operators.
25///
26/// An integer of every width and a `numeric` compare by value, as `int48eq`, or `numeric_eq` after
27/// `int8_numeric`, compares them, so `4`, `4::bigint` and `4.00` are one value. A `date` compares
28/// with a `timestamp` as `date_cmp_timestamp` does, equal to its midnight. A `text` compares by
29/// its bytes, as under the `C` collation, and so do the strings in a `jsonb`. A `uuid` compares by
30/// its bytes, as `uuid_cmp` does. Each remaining variant has a separate comparison family,
31/// ordered after `uuid` in the order `bpchar`, `timestamptz`, `time`, `timetz`, `interval`.
32/// Cross-family comparisons require the caller's coercion and session settings.
33///
34/// Its [`Display`](fmt::Display) uses `DateStyle` `ISO`, `TimeZone` `UTC` and `IntervalStyle`
35/// `postgres`, as [`CastValue`]'s does.
36///
37/// ```
38/// extern crate alloc;
39///
40/// use alloc::collections::BTreeSet;
41///
42/// use sql_values::postgres::{InputContext, PgDate, PgNumeric, PgTimestamp, PgValue};
43///
44/// let four = PgValue::Numeric(PgNumeric::parse("4.00").unwrap());
45/// assert_eq!(PgValue::Integer(4), four);
46/// assert!(PgValue::Integer(5) > four);
47/// assert_eq!(BTreeSet::from([PgValue::Integer(4), four]).len(), 1);
48///
49/// let day = PgValue::Date(PgDate::from_ymd(2026, 1, 1).unwrap());
50/// let midnight = PgTimestamp::parse("2026-01-01 00:00", InputContext::new()).unwrap();
51/// assert_eq!(day, PgValue::Timestamp(midnight));
52///
53/// assert!(PgValue::Text("B".into()) < PgValue::Text("a".into()));
54/// assert!(PgValue::Boolean(true) < PgValue::Integer(0));
55/// assert_eq!(PgValue::Boolean(true).to_string(), "t");
56/// ```
57#[derive(Debug, Clone)]
58pub enum PgValue {
59    /// A `boolean`, `false` before `true`.
60    Boolean(bool),
61    /// A `smallint`, `integer` or `bigint`, whichever its width.
62    Integer(i64),
63    /// A `numeric`.
64    Numeric(PgNumeric),
65    /// A `text` or `varchar`.
66    Text(String),
67    /// A `date`.
68    Date(PgDate),
69    /// A `timestamp`.
70    Timestamp(PgTimestamp),
71    /// An array of values over its dimensions, in row-major order.
72    Array(PgArray),
73    /// A `jsonb`.
74    Jsonb(PgJsonb),
75    /// A `uuid`.
76    Uuid(PgUuid),
77    /// A `char(n)`, compared without trailing spaces under the `C` collation.
78    Bpchar(PgBpchar<'static>),
79    /// A `timestamptz`, compared by instant.
80    TimestampTz(PgTimestampTz),
81    /// A `time`.
82    Time(PgTime),
83    /// A `timetz`, compared by UTC time and then by offset west of UTC.
84    TimeTz(PgTimeTz),
85    /// An `interval`, compared with months as 30 days and days as 24 hours.
86    Interval(PgInterval),
87}
88
89impl PgValue {
90    /// The rank of the value's types among the ones PostgreSQL has no operator between.
91    const fn family(&self) -> u8 {
92        match self {
93            Self::Boolean(_) => 0,
94            Self::Integer(_) | Self::Numeric(_) => 1,
95            Self::Text(_) => 2,
96            Self::Date(_) | Self::Timestamp(_) => 3,
97            Self::Array(_) => 4,
98            Self::Jsonb(_) => 5,
99            Self::Uuid(_) => 6,
100            Self::Bpchar(_) => 7,
101            Self::TimestampTz(_) => 8,
102            Self::Time(_) => 9,
103            Self::TimeTz(_) => 10,
104            Self::Interval(_) => 11,
105        }
106    }
107
108    /// The value as a [`CastValue`], an integer held as `integer`.
109    ///
110    /// # Errors
111    ///
112    /// [`CastError::OutOfRange`] for an integer outside [`IntegerType::range`].
113    ///
114    /// ```
115    /// use sql_values::postgres::{CastError, CastValue, IntegerType, BuiltinType, PgValue};
116    ///
117    /// let value = || PgValue::Integer(40_000);
118    /// let held = value().into_cast_value(IntegerType::Integer);
119    /// assert_eq!(held, Ok(CastValue::Integer(40_000)));
120    /// assert_eq!(
121    ///     value().into_cast_value(IntegerType::Smallint),
122    ///     Err(CastError::OutOfRange(BuiltinType::Smallint)),
123    /// );
124    /// assert_eq!(PgValue::from(CastValue::Smallint(7)), PgValue::Integer(7));
125    /// ```
126    pub fn into_cast_value(self, integer: IntegerType) -> Result<CastValue, CastError> {
127        Ok(match self {
128            Self::Boolean(value) => CastValue::Boolean(value),
129            Self::Integer(value) => return integer.value(value),
130            Self::Numeric(value) => CastValue::Numeric(value),
131            Self::Text(text) => CastValue::Text(text),
132            Self::Date(date) => CastValue::Date(date),
133            Self::Timestamp(at) => CastValue::Timestamp(at),
134            Self::Jsonb(value) => CastValue::Jsonb(value),
135            Self::Uuid(value) => CastValue::Uuid(value),
136            Self::Bpchar(value) => CastValue::Bpchar(value),
137            Self::TimestampTz(value) => CastValue::TimestampTz(value),
138            Self::Time(value) => CastValue::Time(value),
139            Self::TimeTz(value) => CastValue::TimeTz(value),
140            Self::Interval(value) => CastValue::Interval(value),
141            Self::Array(_) => return Err(CastError::Unsupported),
142        })
143    }
144
145    /// The `numeric` of an integer, as `int8_numeric` makes it, or a `numeric` itself.
146    #[must_use]
147    pub fn as_numeric(&self) -> Option<PgNumeric> {
148        match self {
149            Self::Integer(value) => Some(PgNumeric::from(*value)),
150            Self::Numeric(value) => Some(value.clone()),
151            _ => None,
152        }
153    }
154
155    /// The text of a `text`.
156    #[must_use]
157    pub fn as_text(&self) -> Option<&str> {
158        match self {
159            Self::Text(text) => Some(text),
160            _ => None,
161        }
162    }
163
164    /// A `date`.
165    #[must_use]
166    pub const fn as_date(&self) -> Option<PgDate> {
167        match self {
168            Self::Date(date) => Some(*date),
169            _ => None,
170        }
171    }
172
173    /// The `timestamp` the value equals, a `timestamp` itself or a `date`'s midnight, which a date
174    /// from 294277-01-01 has none of.
175    ///
176    /// ```
177    /// use sql_values::postgres::{PgDate, PgValue};
178    ///
179    /// let day = PgValue::Date(PgDate::from_ymd(2026, 1, 1).unwrap());
180    /// assert_eq!(day.as_timestamp().unwrap().to_string(), "2026-01-01 00:00:00");
181    /// let late = PgValue::Date(PgDate::from_ymd(294_277, 1, 1).unwrap());
182    /// assert_eq!(late.as_timestamp(), None);
183    /// ```
184    #[must_use]
185    pub fn as_timestamp(&self) -> Option<PgTimestamp> {
186        match self {
187            Self::Date(date) => date.to_timestamp().ok(),
188            Self::Timestamp(at) => Some(*at),
189            _ => None,
190        }
191    }
192
193    /// The type's output function, or `None` when session settings decide its spelling.
194    ///
195    /// ```
196    /// use sql_values::postgres::{PgDate, PgValue};
197    ///
198    /// let flag = PgValue::Boolean(false);
199    /// assert_eq!(flag.output().map(|output| output.to_string()).as_deref(), Some("f"));
200    /// assert!(PgValue::Date(PgDate::from_ymd(2026, 1, 1).unwrap()).output().is_none());
201    /// ```
202    #[must_use]
203    pub fn output(&self) -> Option<impl fmt::Display + '_> {
204        self.has_stable_output().then_some(self)
205    }
206
207    /// Whether output is independent of session settings, including nested array elements.
208    fn has_stable_output(&self) -> bool {
209        match self {
210            Self::Date(_) | Self::Timestamp(_) | Self::TimestampTz(_) | Self::Interval(_) => false,
211            Self::Array(array) => array
212                .elements()
213                .iter()
214                .flatten()
215                .all(Self::has_stable_output),
216            _ => true,
217        }
218    }
219}
220
221/// Preserves every value represented by [`CastValue`].
222impl From<CastValue> for PgValue {
223    fn from(value: CastValue) -> Self {
224        match value {
225            CastValue::Boolean(value) => Self::Boolean(value),
226            CastValue::Smallint(value) => Self::Integer(value.into()),
227            CastValue::Integer(value) => Self::Integer(value.into()),
228            CastValue::Bigint(value) => Self::Integer(value),
229            CastValue::Numeric(value) => Self::Numeric(value),
230            CastValue::Text(text) => Self::Text(text),
231            CastValue::Date(date) => Self::Date(date),
232            CastValue::Timestamp(at) => Self::Timestamp(at),
233            CastValue::Jsonb(value) => Self::Jsonb(value),
234            CastValue::Uuid(value) => Self::Uuid(value),
235            CastValue::Bpchar(value) => Self::Bpchar(value),
236            CastValue::TimestampTz(value) => Self::TimestampTz(value),
237            CastValue::Time(value) => Self::Time(value),
238            CastValue::TimeTz(value) => Self::TimeTz(value),
239            CastValue::Interval(value) => Self::Interval(value),
240        }
241    }
242}
243
244impl PartialEq for PgValue {
245    fn eq(&self, other: &Self) -> bool {
246        self.cmp(other) == Ordering::Equal
247    }
248}
249
250impl Eq for PgValue {}
251
252impl PartialOrd for PgValue {
253    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
254        Some(self.cmp(other))
255    }
256}
257
258impl Ord for PgValue {
259    fn cmp(&self, other: &Self) -> Ordering {
260        match (self, other) {
261            (Self::Boolean(left), Self::Boolean(right)) => left.cmp(right),
262            (Self::Integer(left), Self::Integer(right)) => left.cmp(right),
263            (Self::Integer(left), Self::Numeric(right)) => right.cmp_integer(*left).reverse(),
264            (Self::Numeric(left), Self::Integer(right)) => left.cmp_integer(*right),
265            (Self::Numeric(left), Self::Numeric(right)) => left.cmp(right),
266            (Self::Text(left), Self::Text(right)) => left.cmp(right),
267            (Self::Date(left), Self::Date(right)) => left.cmp(right),
268            (Self::Date(left), Self::Timestamp(right)) => left.cmp_timestamp(*right),
269            (Self::Timestamp(left), Self::Date(right)) => right.cmp_timestamp(*left).reverse(),
270            (Self::Timestamp(left), Self::Timestamp(right)) => left.cmp(right),
271            (Self::Array(left), Self::Array(right)) => left.cmp(right),
272            (Self::Jsonb(left), Self::Jsonb(right)) => left.cmp(right),
273            (Self::Uuid(left), Self::Uuid(right)) => left.cmp(right),
274            (Self::Bpchar(left), Self::Bpchar(right)) => left.as_text().cmp(right.as_text()),
275            (Self::TimestampTz(left), Self::TimestampTz(right)) => left.cmp(right),
276            (Self::Time(left), Self::Time(right)) => left.cmp(right),
277            (Self::TimeTz(left), Self::TimeTz(right)) => left.cmp(right),
278            (Self::Interval(left), Self::Interval(right)) => left.cmp(right),
279            (left, right) => left.family().cmp(&right.family()),
280        }
281    }
282}
283
284impl Hash for PgValue {
285    fn hash<H: Hasher>(&self, state: &mut H) {
286        self.family().hash(state);
287        match self {
288            Self::Boolean(value) => value.hash(state),
289            Self::Integer(value) => PgNumeric::hash_integer(*value, state),
290            Self::Numeric(value) => value.hash(state),
291            Self::Text(text) => text.hash(state),
292            // A date past every timestamp equals none of them.
293            Self::Date(date) => match date.to_timestamp() {
294                Ok(at) => at.hash(state),
295                Err(_) => date.hash(state),
296            },
297            Self::Timestamp(at) => at.hash(state),
298            Self::Array(array) => array.hash(state),
299            Self::Jsonb(value) => value.hash(state),
300            Self::Uuid(value) => value.hash(state),
301            Self::Bpchar(value) => value.hash(state),
302            Self::TimestampTz(value) => value.hash(state),
303            Self::Time(value) => value.hash(state),
304            Self::TimeTz(value) => value.hash(state),
305            Self::Interval(value) => value.hash(state),
306        }
307    }
308}
309
310impl fmt::Display for PgValue {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        match self {
313            Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
314            Self::Integer(value) => write!(f, "{value}"),
315            Self::Numeric(value) => write!(f, "{value}"),
316            Self::Text(text) => f.write_str(text),
317            Self::Date(date) => write!(f, "{date}"),
318            Self::Timestamp(at) => write!(f, "{at}"),
319            Self::Array(array) => write!(f, "{array}"),
320            Self::Jsonb(value) => write!(f, "{value}"),
321            Self::Uuid(value) => write!(f, "{value}"),
322            Self::Bpchar(value) => write!(f, "{value}"),
323            Self::TimestampTz(value) => write!(f, "{value}"),
324            Self::Time(value) => write!(f, "{value}"),
325            Self::TimeTz(value) => write!(f, "{value}"),
326            Self::Interval(value) => write!(f, "{value}"),
327        }
328    }
329}