Skip to main content

uqa_sql/catalog/collations/
selection.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7/// A collation that analysis selected for a call's inputs: one of the fixed built-in collations, or the indeterminate selection that `PostgreSQL` records as `InvalidOid`. It occupies one byte, so retaining it keeps a call binding within its shared expression storage bound, and it is serialized as the `PostgreSQL` collation OID, with zero for the indeterminate selection.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct CollationSelection(u8);
10
11impl CollationSelection {
12    pub const INDETERMINATE: Self = Self(0);
13
14    /// The selection of `oid`, where zero is indeterminate; `None` for an OID that names no built-in collation.
15    #[must_use]
16    pub fn from_oid(oid: u32) -> Option<Self> {
17        if oid == 0 {
18            return Some(Self::INDETERMINATE);
19        }
20        super::BUILTIN_COLLATIONS
21            .iter()
22            .position(|(_, candidate, ..)| *candidate == i64::from(oid))
23            .map(|index| Self(u8::try_from(index + 1).expect("built-in collation table index")))
24    }
25
26    /// The selected collation OID, or zero when the selection is indeterminate.
27    #[must_use]
28    pub fn oid(self) -> u32 {
29        match self.0 {
30            0 => 0,
31            index => u32::try_from(super::BUILTIN_COLLATIONS[usize::from(index) - 1].1)
32                .expect("built-in collation OID"),
33        }
34    }
35}
36
37impl serde::Serialize for CollationSelection {
38    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
39        serializer.serialize_u32(self.oid())
40    }
41}
42
43impl<'de> serde::Deserialize<'de> for CollationSelection {
44    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
45        let oid = <u32 as serde::Deserialize>::deserialize(deserializer)?;
46        Self::from_oid(oid).ok_or_else(|| {
47            serde::de::Error::custom(format!("collation {oid} is not a built-in collation"))
48        })
49    }
50}
51
52#[cfg(test)]
53mod tests;