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