1use core::cmp::Ordering;
22use core::fmt;
23
24use crate::error::{Error, Result};
25
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33pub struct VersionId(String);
34
35impl VersionId {
36 #[must_use]
38 pub fn new(v: impl Into<String>) -> Self {
39 Self(v.into())
40 }
41
42 #[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#[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,
74 Libc,
77 C,
79}
80
81#[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 #[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 #[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 #[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 #[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 #[must_use]
162 pub fn with_encoding(mut self, encoding: impl Into<String>) -> Self {
163 self.encoding = encoding.into();
164 self
165 }
166
167 #[must_use]
169 pub const fn provider(&self) -> PostgresProvider {
170 self.provider
171 }
172
173 #[must_use]
175 pub fn locale(&self) -> &str {
176 &self.locale
177 }
178
179 #[must_use]
181 pub const fn deterministic(&self) -> bool {
182 self.deterministic
183 }
184
185 #[must_use]
187 pub const fn version(&self) -> &VersionId {
188 &self.version
189 }
190
191 #[must_use]
193 pub fn rules(&self) -> Option<&str> {
194 self.rules.as_deref()
195 }
196
197 #[must_use]
199 pub fn encoding(&self) -> &str {
200 &self.encoding
201 }
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
207#[non_exhaustive]
208pub enum MysqlUcaVersion {
209 Uca400,
211 Uca900,
213}
214
215impl MysqlUcaVersion {
216 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
229pub enum Pad {
230 NoPad,
232 Space,
234}
235
236#[derive(Debug, Clone, PartialEq, Eq, Hash)]
238#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
239#[non_exhaustive]
240pub struct MysqlCollation {
241 pub name: String,
243 pub uca_version: MysqlUcaVersion,
245 pub pad: Pad,
247}
248
249impl MysqlCollation {
250 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
288#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
289#[non_exhaustive]
290pub enum OracleProvider {
291 Binary,
293 Uca,
295}
296
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
299#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
300#[non_exhaustive]
301pub enum OracleUcaVersion {
302 Uca700,
304 Uca1210,
306}
307
308impl OracleUcaVersion {
309 #[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 #[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#[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 nls_sort: String,
342 uca_version: Option<OracleUcaVersion>,
343 charset: String,
346 blank_padded: bool,
348}
349
350impl OracleCollation {
351 #[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 #[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 #[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 _ => (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 #[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 #[must_use]
409 pub const fn provider(&self) -> OracleProvider {
410 self.provider
411 }
412
413 #[must_use]
415 pub fn nls_sort(&self) -> &str {
416 &self.nls_sort
417 }
418
419 #[must_use]
421 pub const fn uca_version(&self) -> Option<OracleUcaVersion> {
422 self.uca_version
423 }
424
425 #[must_use]
427 pub fn charset(&self) -> &str {
428 &self.charset
429 }
430
431 #[must_use]
433 pub const fn blank_padded(&self) -> bool {
434 self.blank_padded
435 }
436}
437
438#[derive(Debug, Clone, PartialEq, Eq, Hash)]
440#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
441#[non_exhaustive]
442pub enum Backend {
443 Binary,
445 PostgresIcu(PostgresCollation),
447 MysqlUca(MysqlCollation),
449 Oracle(OracleCollation),
451}
452
453#[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 #[must_use]
487 pub const fn binary() -> Self {
488 Self {
489 backend: Backend::Binary,
490 }
491 }
492
493 #[must_use]
495 pub const fn postgres_c() -> Self {
496 Self::binary()
497 }
498
499 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 #[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 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 #[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 #[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 #[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 #[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 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" => 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 #[must_use]
655 pub const fn backend(&self) -> &Backend {
656 &self.backend
657 }
658
659 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 pub fn equal(&self, a: &str, b: &str) -> Result<bool> {
692 Ok(self.compare(a, b)? == Ordering::Equal)
693 }
694
695 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}