Skip to main content

db_collation/
spec.rs

1// Copyright 2026 db-collation contributors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The closed set of collations this crate reproduces exactly.
16//!
17//! A [`Collation`] is a *resolved description*: the caller reads the source
18//! database's catalog/metadata (or knows it statically) and passes the result
19//! in. This crate never performs that discovery itself.
20
21use core::cmp::Ordering;
22use core::fmt;
23
24use crate::error::{Error, Result};
25
26/// A provider-specific collation data version token.
27///
28/// For `PostgreSQL` ICU this is the `collversion` reported by
29/// `pg_collation_actual_version(oid)`, e.g. `153.128`. For `MySQL` it is the
30/// UCA version implied by the collation name, e.g. `9.0.0`.
31#[derive(Debug, Clone, PartialEq, Eq, Hash)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33pub struct VersionId(String);
34
35impl VersionId {
36    /// Construct a version token from anything string-like.
37    #[must_use]
38    pub fn new(v: impl Into<String>) -> Self {
39        Self(v.into())
40    }
41
42    /// The token as a string slice.
43    #[must_use]
44    pub fn as_str(&self) -> &str {
45        &self.0
46    }
47}
48
49impl From<String> for VersionId {
50    fn from(v: String) -> Self {
51        Self(v)
52    }
53}
54
55impl From<&str> for VersionId {
56    fn from(v: &str) -> Self {
57        Self(v.to_owned())
58    }
59}
60
61impl fmt::Display for VersionId {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.write_str(&self.0)
64    }
65}
66
67/// `PostgreSQL` collation provider.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70#[non_exhaustive]
71pub enum PostgresProvider {
72    /// ICU provider (`collprovider = 'i'`).
73    Icu,
74    /// libc provider (`collprovider = 'c'`). Only `C`/`POSIX` are supported and
75    /// they are bytewise.
76    Libc,
77    /// The `C`/`POSIX` locale under any provider: bytewise ordering.
78    C,
79}
80
81/// A resolved `PostgreSQL` collation description.
82///
83/// Fields are private; use the constructors and [`PostgresCollation::with_rules`]
84/// / [`PostgresCollation::with_encoding`] to build one. `rules` and `encoding`
85/// are part of the identity: a custom-rule collation or a non-UTF-8 source is
86/// not reproducible by this crate and is refused at construction.
87#[derive(Debug, Clone, PartialEq, Eq, Hash)]
88#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
89#[non_exhaustive]
90pub struct PostgresCollation {
91    provider: PostgresProvider,
92    locale: String,
93    deterministic: bool,
94    version: VersionId,
95    rules: Option<String>,
96    encoding: String,
97}
98
99impl PostgresCollation {
100    /// Bytewise `C`/`POSIX` collation.
101    ///
102    /// The comparison is bytewise, but the library only supports UTF-8 sources,
103    /// so a non-UTF-8 source is still refused at construction (the `encoding`
104    /// field defaults to `UTF8`; use [`PostgresCollation::with_encoding`] to
105    /// describe another).
106    #[must_use]
107    pub fn c() -> Self {
108        Self {
109            provider: PostgresProvider::C,
110            locale: String::new(),
111            deterministic: true,
112            version: VersionId::new("c"),
113            rules: None,
114            encoding: "UTF8".to_owned(),
115        }
116    }
117
118    /// A `PostgreSQL` ICU collation description with no custom rules, assuming a
119    /// UTF-8 source. Use [`PostgresCollation::with_rules`] /
120    /// [`PostgresCollation::with_encoding`] to describe other sources.
121    #[must_use]
122    pub fn icu(locale: impl Into<String>, deterministic: bool, version: VersionId) -> Self {
123        Self {
124            provider: PostgresProvider::Icu,
125            locale: locale.into(),
126            deterministic,
127            version,
128            rules: None,
129            encoding: "UTF8".to_owned(),
130        }
131    }
132
133    /// A `PostgreSQL` libc collation description. Only `C`/`POSIX` are
134    /// reproducible (bytewise); any other libc locale is refused at
135    /// construction. Use [`PostgresCollation::c`] for the `C` locale directly.
136    #[must_use]
137    pub fn libc(locale: impl Into<String>) -> Self {
138        Self {
139            provider: PostgresProvider::Libc,
140            locale: locale.into(),
141            deterministic: true,
142            version: VersionId::new("libc"),
143            rules: None,
144            encoding: "UTF8".to_owned(),
145        }
146    }
147
148    /// Attach custom ICU collation rules (`collicurules`).
149    ///
150    /// The library refuses **any** value here at construction — including the
151    /// empty string — with `Error::Unsupported`. Custom ICU rules are not
152    /// reproducible exactly; do not compare such a collation locally.
153    #[must_use]
154    pub fn with_rules(mut self, rules: impl Into<String>) -> Self {
155        self.rules = Some(rules.into());
156        self
157    }
158
159    /// Set the source encoding (`pg_collation`/database encoding, e.g. `UTF8`,
160    /// `LATIN1`).
161    #[must_use]
162    pub fn with_encoding(mut self, encoding: impl Into<String>) -> Self {
163        self.encoding = encoding.into();
164        self
165    }
166
167    /// The provider.
168    #[must_use]
169    pub const fn provider(&self) -> PostgresProvider {
170        self.provider
171    }
172
173    /// ICU locale id (empty for `C`).
174    #[must_use]
175    pub fn locale(&self) -> &str {
176        &self.locale
177    }
178
179    /// Whether the source collation is deterministic.
180    #[must_use]
181    pub const fn deterministic(&self) -> bool {
182        self.deterministic
183    }
184
185    /// The source collation data version (`collversion`).
186    #[must_use]
187    pub const fn version(&self) -> &VersionId {
188        &self.version
189    }
190
191    /// Custom ICU collation rules, if any.
192    #[must_use]
193    pub fn rules(&self) -> Option<&str> {
194        self.rules.as_deref()
195    }
196
197    /// The source encoding.
198    #[must_use]
199    pub fn encoding(&self) -> &str {
200        &self.encoding
201    }
202}
203
204/// `MySQL` UCA weight-table version.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
207#[non_exhaustive]
208pub enum MysqlUcaVersion {
209    /// UCA 4.0.0, used by `utf8mb4_unicode_ci` and friends.
210    Uca400,
211    /// UCA 9.0.0, used by `utf8mb4_0900_ai_ci` and friends.
212    Uca900,
213}
214
215impl MysqlUcaVersion {
216    /// The canonical version token.
217    #[must_use]
218    pub fn version_id(self) -> VersionId {
219        match self {
220            Self::Uca400 => VersionId::new("4.0.0"),
221            Self::Uca900 => VersionId::new("9.0.0"),
222        }
223    }
224}
225
226/// Trailing-space comparison semantics.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
229pub enum Pad {
230    /// Trailing spaces are significant (NO PAD; the `utf8mb4_0900_*` family).
231    NoPad,
232    /// Trailing spaces are ignored (PAD SPACE; UCA 4.0.0 collations).
233    Space,
234}
235
236/// A resolved `MySQL` collation description.
237#[derive(Debug, Clone, PartialEq, Eq, Hash)]
238#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
239#[non_exhaustive]
240pub struct MysqlCollation {
241    /// The collation name, e.g. `utf8mb4_0900_ai_ci`.
242    pub name: String,
243    /// The UCA version of its weight table.
244    pub uca_version: MysqlUcaVersion,
245    /// Padding semantics.
246    pub pad: Pad,
247}
248
249impl MysqlCollation {
250    /// Build a `MySQL` UCA collation description from its resolved parts.
251    #[must_use]
252    pub fn new(name: impl Into<String>, uca_version: MysqlUcaVersion, pad: Pad) -> Self {
253        Self {
254            name: name.into(),
255            uca_version,
256            pad,
257        }
258    }
259
260    /// `utf8mb4_0900_ai_ci`: UCA 9.0.0, accent- and case-insensitive, NO PAD.
261    #[must_use]
262    pub fn utf8mb4_0900_ai_ci() -> Self {
263        Self {
264            name: "utf8mb4_0900_ai_ci".to_owned(),
265            uca_version: MysqlUcaVersion::Uca900,
266            pad: Pad::NoPad,
267        }
268    }
269
270    /// `utf8mb4_unicode_ci`: UCA 4.0.0, accent- and case-insensitive, PAD SPACE.
271    #[must_use]
272    pub fn utf8mb4_unicode_ci() -> Self {
273        Self {
274            name: "utf8mb4_unicode_ci".to_owned(),
275            uca_version: MysqlUcaVersion::Uca400,
276            pad: Pad::Space,
277        }
278    }
279}
280
281/// `Oracle` collation provider.
282///
283/// Oracle compares character data under a *named collation* selected by
284/// `NLS_SORT`. Only two families are reproducible by this crate: the bytewise
285/// `BINARY` collation and the `UCA*_DUCET` Unicode Collation Algorithm
286/// collations built from the open DUCET tables.
287#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
288#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
289#[non_exhaustive]
290pub enum OracleProvider {
291    /// Bytewise comparison (`NLS_SORT=BINARY`) — the `Binary` backend.
292    Binary,
293    /// A `UCA*_DUCET` collation backed by an open DUCET weight table.
294    Uca,
295}
296
297/// `Oracle` UCA version for a `UCA*_DUCET` collation.
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
299#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
300#[non_exhaustive]
301pub enum OracleUcaVersion {
302    /// `UCA0700_DUCET` — Unicode 7.0.0 DUCET.
303    Uca700,
304    /// `UCA1210_DUCET` — Unicode 12.1.0 DUCET.
305    Uca1210,
306}
307
308impl OracleUcaVersion {
309    /// The canonical version token.
310    #[must_use]
311    pub fn version_id(self) -> VersionId {
312        match self {
313            Self::Uca700 => VersionId::new("7.0.0"),
314            Self::Uca1210 => VersionId::new("12.1.0"),
315        }
316    }
317
318    /// The `Oracle` collation name this version corresponds to.
319    #[must_use]
320    pub const fn collation_name(self) -> &'static str {
321        match self {
322            Self::Uca700 => "UCA0700_DUCET",
323            Self::Uca1210 => "UCA1210_DUCET",
324        }
325    }
326}
327
328/// A resolved `Oracle` collation description.
329///
330/// Fields are private; use the constructors. Only `NLS_SORT=BINARY` on an
331/// `AL32UTF8` database with `VARCHAR2` semantics, and the `UCA0700_DUCET` /
332/// `UCA1210_DUCET` collations, are reproducible. Every other Oracle collation
333/// (monolingual, `_M`, `BINARY_CI`/`BINARY_AI`, `*_ROOT`, `*_ORADUCET`, the
334/// tailored UCA collations) is refused at construction.
335#[derive(Debug, Clone, PartialEq, Eq, Hash)]
336#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
337#[non_exhaustive]
338pub struct OracleCollation {
339    provider: OracleProvider,
340    /// The resolved `NLS_SORT` name (normalized), e.g. `BINARY`, `UCA1210_DUCET`.
341    nls_sort: String,
342    uca_version: Option<OracleUcaVersion>,
343    // Only AL32UTF8 is modelled. Kept explicit so a wrong source is refused
344    // rather than silently compared with the wrong bytes.
345    charset: String,
346    // `CHAR` is blank-padded; `VARCHAR2` is not. Only the latter is modelled.
347    blank_padded: bool,
348}
349
350impl OracleCollation {
351    /// Bytewise `NLS_SORT=BINARY` on an `AL32UTF8` `VARCHAR2`.
352    #[must_use]
353    pub fn binary() -> Self {
354        Self {
355            provider: OracleProvider::Binary,
356            nls_sort: "BINARY".to_owned(),
357            uca_version: None,
358            charset: "AL32UTF8".to_owned(),
359            blank_padded: false,
360        }
361    }
362
363    /// A `UCA*_DUCET` collation on an `AL32UTF8` `VARCHAR2`.
364    #[must_use]
365    pub fn uca_ducet(version: OracleUcaVersion) -> Self {
366        Self {
367            provider: OracleProvider::Uca,
368            nls_sort: version.collation_name().to_owned(),
369            uca_version: Some(version),
370            charset: "AL32UTF8".to_owned(),
371            blank_padded: false,
372        }
373    }
374
375    /// Build a description from a raw resolved `NLS_SORT` name and source
376    /// charset. The name is normalized (trimmed, upper-cased). Unknown or
377    /// unsupported names are refused at [`Collation::oracle`].
378    #[must_use]
379    pub fn from_nls_sort(nls_sort: impl Into<String>, charset: impl Into<String>) -> Self {
380        let name = nls_sort.into().trim().to_ascii_uppercase();
381        let (provider, uca_version) = match name.as_str() {
382            "UCA0700_DUCET" => (OracleProvider::Uca, Some(OracleUcaVersion::Uca700)),
383            "UCA1210_DUCET" => (OracleProvider::Uca, Some(OracleUcaVersion::Uca1210)),
384            // `BINARY` and anything else: unsupported names are refused at
385            // construction; only `BINARY` is a valid binary-provider name.
386            _ => (OracleProvider::Binary, None),
387        };
388        Self {
389            provider,
390            nls_sort: name,
391            uca_version,
392            charset: charset.into(),
393            blank_padded: false,
394        }
395    }
396
397    /// Mark the source as a blank-padded `CHAR`/`NCHAR` column.
398    ///
399    /// Blank-padded comparison differs from `VARCHAR2` even under the same
400    /// collation, so any blank-padded source is refused at construction.
401    #[must_use]
402    pub fn with_blank_padded(mut self, blank_padded: bool) -> Self {
403        self.blank_padded = blank_padded;
404        self
405    }
406
407    /// The provider.
408    #[must_use]
409    pub const fn provider(&self) -> OracleProvider {
410        self.provider
411    }
412
413    /// The resolved `NLS_SORT` name.
414    #[must_use]
415    pub fn nls_sort(&self) -> &str {
416        &self.nls_sort
417    }
418
419    /// The UCA version, for `UCA*_DUCET` collations.
420    #[must_use]
421    pub const fn uca_version(&self) -> Option<OracleUcaVersion> {
422        self.uca_version
423    }
424
425    /// The source character set (only `AL32UTF8` is modelled).
426    #[must_use]
427    pub fn charset(&self) -> &str {
428        &self.charset
429    }
430
431    /// Whether the source is blank-padded (`CHAR`/`NCHAR`).
432    #[must_use]
433    pub const fn blank_padded(&self) -> bool {
434        self.blank_padded
435    }
436}
437
438/// Which backend a [`Collation`] uses.
439#[derive(Debug, Clone, PartialEq, Eq, Hash)]
440#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
441#[non_exhaustive]
442pub enum Backend {
443    /// Bytewise comparison (`PostgreSQL` `C`/`POSIX`, `MySQL` `*_bin`).
444    Binary,
445    /// `PostgreSQL` ICU.
446    PostgresIcu(PostgresCollation),
447    /// `MySQL` UCA weight tables.
448    MysqlUca(MysqlCollation),
449    /// `Oracle` (bytewise `BINARY` or `UCA*_DUCET`).
450    Oracle(OracleCollation),
451}
452
453/// A collation that this crate can compare with, or an explicit refusal.
454///
455/// Construct one of these, then call [`Collation::compare`]. Construction fails
456/// closed: anything not modelled exactly yields [`Error`].
457///
458/// Serialization round-trips the *description* ([`Backend`]); deserialization
459/// re-runs the same validated construction, so a tampered or stale payload
460/// cannot produce an unchecked `Collation`.
461#[derive(Debug, Clone, PartialEq, Eq, Hash)]
462#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
463#[cfg_attr(feature = "serde", serde(try_from = "Backend", into = "Backend"))]
464pub struct Collation {
465    backend: Backend,
466}
467
468#[cfg(feature = "serde")]
469impl TryFrom<Backend> for Collation {
470    type Error = Error;
471
472    fn try_from(backend: Backend) -> Result<Self> {
473        Self::from_backend(backend)
474    }
475}
476
477#[cfg(feature = "serde")]
478impl From<Collation> for Backend {
479    fn from(collation: Collation) -> Self {
480        collation.backend
481    }
482}
483
484impl Collation {
485    /// Bytewise comparison. Always available.
486    #[must_use]
487    pub const fn binary() -> Self {
488        Self {
489            backend: Backend::Binary,
490        }
491    }
492
493    /// `PostgreSQL` `C`/`POSIX`, bytewise.
494    #[must_use]
495    pub const fn postgres_c() -> Self {
496        Self::binary()
497    }
498
499    /// Construct a `PostgreSQL` ICU collation, validating the version at runtime.
500    ///
501    /// Returns [`Error::VersionMismatch`] if `source_version` does not match the
502    /// ICU data the linked backend would use, and [`Error::Unsupported`] for
503    /// custom rules or non-ICU providers.
504    pub fn postgres_icu(
505        locale: impl Into<String>,
506        deterministic: bool,
507        source_version: VersionId,
508    ) -> Result<Self> {
509        let spec = PostgresCollation::icu(locale, deterministic, source_version);
510        Self::postgres(spec)
511    }
512
513    /// Construct a collation from a fully resolved `PostgreSQL` description.
514    ///
515    /// Refuses configurations this crate cannot reproduce exactly: libc
516    /// providers other than `C`/`POSIX`, custom ICU rules, and non-UTF-8
517    /// sources.
518    #[allow(clippy::needless_pass_by_value)]
519    pub fn postgres(spec: PostgresCollation) -> Result<Self> {
520        if !spec.encoding().eq_ignore_ascii_case("UTF8") {
521            return Err(Error::unsupported(
522                "postgres",
523                spec.locale(),
524                "only UTF-8 sources are reproducible; other encodings are refused",
525            ));
526        }
527        if spec.rules().is_some() {
528            return Err(Error::unsupported(
529                "postgres",
530                spec.locale(),
531                "custom ICU collation rules (collicurules) are not reproducible",
532            ));
533        }
534        match spec.provider() {
535            PostgresProvider::C => Ok(Self::binary()),
536            PostgresProvider::Libc => {
537                // `C`/`POSIX` under libc are bytewise and reproducible; other
538                // libc locales depend on the host OS locale database and are not.
539                let locale = spec.locale();
540                if locale.eq_ignore_ascii_case("C") || locale.eq_ignore_ascii_case("POSIX") {
541                    Ok(Self::binary())
542                } else {
543                    Err(Error::unsupported(
544                        "postgres",
545                        locale,
546                        "libc collations other than C/POSIX are not reproducible portably",
547                    ))
548                }
549            }
550            PostgresProvider::Icu => {
551                #[cfg(feature = "postgres-icu")]
552                {
553                    crate::postgres::validate(&spec)?;
554                    Ok(Self {
555                        backend: Backend::PostgresIcu(spec),
556                    })
557                }
558                #[cfg(not(feature = "postgres-icu"))]
559                {
560                    let _ = spec;
561                    Err(Error::FeatureDisabled {
562                        feature: "postgres-icu",
563                    })
564                }
565            }
566        }
567    }
568
569    /// Construct the modelled `MySQL` `utf8mb4_0900_ai_ci` collation.
570    ///
571    /// Only available with the `mysql-uca` feature (enabled by default). Use
572    /// [`Collation::mysql`] when the feature set is not known at compile time;
573    /// it returns [`Error::FeatureDisabled`] instead.
574    #[cfg(feature = "mysql-uca")]
575    #[must_use]
576    pub fn mysql_0900_ai_ci() -> Self {
577        Self::mysql(MysqlCollation::utf8mb4_0900_ai_ci()).expect("utf8mb4_0900_ai_ci is supported")
578    }
579
580    /// Construct the modelled `MySQL` `utf8mb4_unicode_ci` collation.
581    ///
582    /// Only available with the `mysql-uca` feature (enabled by default). Use
583    /// [`Collation::mysql`] when the feature set is not known at compile time;
584    /// it returns [`Error::FeatureDisabled`] instead.
585    #[cfg(feature = "mysql-uca")]
586    #[must_use]
587    pub fn mysql_unicode_ci() -> Self {
588        Self::mysql(MysqlCollation::utf8mb4_unicode_ci()).expect("utf8mb4_unicode_ci is supported")
589    }
590
591    /// Construct a collation from a fully resolved `MySQL` description.
592    #[allow(clippy::needless_pass_by_value)]
593    pub fn mysql(spec: MysqlCollation) -> Result<Self> {
594        #[cfg(feature = "mysql-uca")]
595        {
596            crate::mysql::validate(&spec)?;
597            Ok(Self {
598                backend: Backend::MysqlUca(spec),
599            })
600        }
601        #[cfg(not(feature = "mysql-uca"))]
602        {
603            let _ = spec;
604            Err(Error::FeatureDisabled {
605                feature: "mysql-uca",
606            })
607        }
608    }
609
610    /// Construct a collation from a fully resolved `Oracle` description.
611    ///
612    /// Only `NLS_SORT=BINARY` on `AL32UTF8` `VARCHAR2` (bytewise) and the
613    /// `UCA0700_DUCET` / `UCA1210_DUCET` collations are reproducible. Every
614    /// other Oracle collation — monolingual, `_M`, `BINARY_CI`/`BINARY_AI`,
615    /// `*_ROOT`, `*_ORADUCET`, tailored UCA, non-`AL32UTF8`, blank-padded — is
616    /// refused with [`Error::Unsupported`].
617    #[allow(clippy::needless_pass_by_value)]
618    pub fn oracle(spec: OracleCollation) -> Result<Self> {
619        #[cfg(feature = "oracle")]
620        {
621            Ok(Self {
622                backend: crate::oracle::validate(&spec)?,
623            })
624        }
625        #[cfg(not(feature = "oracle"))]
626        {
627            let _ = spec;
628            Err(Error::FeatureDisabled { feature: "oracle" })
629        }
630    }
631
632    /// Resolve a `MySQL` collation by name **without a version**, refusing any
633    /// name whose semantics depend on the server version.
634    ///
635    /// This is intentionally conservative. Prefer [`Collation::mysql`] with an
636    /// explicit [`MysqlCollation`] resolved by the caller.
637    pub fn from_mysql_name_unspecified_version(name: &str) -> Result<Self> {
638        match name {
639            "utf8mb4_0900_ai_ci" => Self::mysql(MysqlCollation::utf8mb4_0900_ai_ci()),
640            "utf8mb4_unicode_ci" => Self::mysql(MysqlCollation::utf8mb4_unicode_ci()),
641            // `utf8mb4_0900_bin` is NO PAD and orders by code point; for valid
642            // UTF-8 that is exactly the bytewise `binary` backend. (The legacy
643            // `utf8mb4_bin` is PAD SPACE and is intentionally not mapped here.)
644            "utf8mb4_0900_bin" => Ok(Self::binary()),
645            _ => Err(Error::unsupported(
646                "mysql",
647                name,
648                "unrecognised or version-dependent collation; resolve it explicitly",
649            )),
650        }
651    }
652
653    /// The backend this collation uses.
654    #[must_use]
655    pub const fn backend(&self) -> &Backend {
656        &self.backend
657    }
658
659    /// Compare two UTF-8 strings exactly as the source database would.
660    ///
661    /// This is the primary operation. Sort keys are intentionally not part of
662    /// the stable API: the contract is a three-way comparison, and a collation
663    /// that also defines a bytewise tie-break (`PostgreSQL` deterministic
664    /// collations) cannot be reproduced by a single ICU sort key, which encodes
665    /// only the primary ICU comparison.
666    ///
667    /// Returns [`Error`] if the underlying backend fails at runtime. The binary
668    /// backend never fails; the ICU backend can, and a failed comparison is
669    /// never silently reported as equality.
670    pub fn compare(&self, a: &str, b: &str) -> Result<Ordering> {
671        match &self.backend {
672            Backend::Binary => Ok(a.as_bytes().cmp(b.as_bytes())),
673            #[cfg(feature = "postgres-icu")]
674            Backend::PostgresIcu(spec) => crate::postgres::compare(spec, a, b),
675            #[cfg(not(feature = "postgres-icu"))]
676            Backend::PostgresIcu(_) => unreachable!("postgres backend cannot be constructed"),
677            #[cfg(feature = "mysql-uca")]
678            Backend::MysqlUca(spec) => Ok(crate::mysql::compare(spec, a, b)),
679            #[cfg(not(feature = "mysql-uca"))]
680            Backend::MysqlUca(_) => unreachable!("mysql backend cannot be constructed"),
681            #[cfg(feature = "oracle-uca")]
682            Backend::Oracle(spec) => crate::oracle::compare(spec, a, b),
683            #[cfg(not(feature = "oracle-uca"))]
684            Backend::Oracle(_) => unreachable!("oracle backend cannot be constructed"),
685        }
686    }
687
688    /// Whether `a` and `b` are equal under this collation.
689    ///
690    /// Returns [`Error`] for the same reasons as [`Collation::compare`].
691    pub fn equal(&self, a: &str, b: &str) -> Result<bool> {
692        Ok(self.compare(a, b)? == Ordering::Equal)
693    }
694
695    /// Build a collation from a resolved [`Backend`] description, re-running the
696    /// same validation as the public constructors.
697    ///
698    /// This is the single construction path used by deserialization, so an
699    /// arbitrary or stale description cannot bypass the support boundary.
700    pub fn from_backend(backend: Backend) -> Result<Self> {
701        match backend {
702            Backend::Binary => Ok(Self::binary()),
703            Backend::PostgresIcu(spec) => Self::postgres(spec),
704            Backend::MysqlUca(spec) => Self::mysql(spec),
705            Backend::Oracle(spec) => Self::oracle(spec),
706        }
707    }
708}
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713
714    #[test]
715    fn test_binary_is_bytewise() {
716        let c = Collation::binary();
717        assert_eq!(c.compare("a", "b").unwrap(), Ordering::Less);
718        assert_eq!(c.compare("A", "a").unwrap(), Ordering::Less);
719        assert!(c.equal("a", "a").unwrap());
720    }
721
722    #[test]
723    fn test_postgres_libc_is_refused() {
724        let spec = PostgresCollation::libc("en_US.UTF-8");
725        assert!(Collation::postgres(spec).is_err());
726    }
727
728    #[test]
729    fn test_postgres_libc_c_is_binary() {
730        for locale in ["C", "POSIX", "posix"] {
731            let spec = PostgresCollation::libc(locale);
732            let c = Collation::postgres(spec).unwrap();
733            assert!(matches!(c.backend(), Backend::Binary), "{locale}");
734        }
735    }
736
737    #[test]
738    fn test_unspecified_mysql_name_unknown_is_refused() {
739        assert!(Collation::from_mysql_name_unspecified_version("utf8mb4_general_ci").is_err());
740        assert!(Collation::from_mysql_name_unspecified_version("utf8mb4_zh_0900_as_cs").is_err());
741    }
742
743    #[test]
744    fn test_collation_is_send_sync() {
745        static_assertions::assert_impl_all!(Collation: Send, Sync);
746    }
747
748    #[test]
749    fn test_error_is_fallback() {
750        let e = Error::unsupported("mysql", "x", "y");
751        assert!(e.is_fallback_required());
752    }
753}