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