diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index c0221af..a88755c 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -18,7 +18,7 @@ use crate::domain::exam_question::{ }; use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; -use crate::domain::text_fold::{fold, fold_sql}; +use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -295,7 +295,7 @@ impl BankQuestion { offset: i64, db: &Database, ) -> Result<(Vec, i64), AppError> { - let needle = q.map(|q| fold(q.trim())).filter(|q| !q.is_empty()); + let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); let mut clauses = Vec::new(); if visible_to.is_some() { clauses.push("(visibility = 'school' OR owner = $viewer)"); @@ -309,7 +309,7 @@ impl BankQuestion { if subject.is_some() { clauses.push("subject = $subject"); } - let text_clause = format!("{} CONTAINS $q", fold_sql("text")); + let text_clause = format!("{} CONTAINS $q", search_fold_sql("text")); if needle.is_some() { clauses.push(text_clause.as_str()); } diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 27d5a45..8e115d2 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -439,8 +439,9 @@ fn validate_list(field: &'static str, values: Vec) -> Result } // `to_lowercase` is locale-invariant — `İZİN` lowercases to `i̇zin` (with a // leftover combining dot) and would slip past `izin` as a distinct entry. - // Same folding as search uses, so the whole app agrees on "the same word". - let mut folded: Vec = trimmed.iter().map(|v| text_fold::fold(v)).collect(); + // The *identity* fold, not search's: search deliberately collapses `ü`→`u`, + // which would make a school unable to have both `tur` and `tür`. + let mut folded: Vec = trimmed.iter().map(|v| text_fold::case_fold_tr(v)).collect(); folded.sort_unstable(); folded.dedup(); if folded.len() != trimmed.len() { @@ -560,6 +561,32 @@ mod tests { ); } + /// Dedup folds *case*, not letters. The search fold collapses `ü`→`u`, so + /// using it here made genuinely distinct Turkish words un-listable: a + /// school could not have both a `tur` and a `tür`. + #[tokio::test] + async fn distinct_turkish_words_are_not_duplicates() { + let with_kinds = |exam_kinds| { + Settings::try_new(SettingsParams { + exam_kinds, + ..params() + }) + }; + assert!(with_kinds(kinds(&["tur", "tür"])).is_ok()); + assert!(with_kinds(kinds(&["kir", "kır"])).is_ok()); + // A true case variant of one of them is still a duplicate. + assert!(with_kinds(kinds(&["tür", "TÜR"])).is_err()); + assert!(with_kinds(kinds(&["kır", "KIR"])).is_err()); + // Same on the other guarded list. + assert!( + Settings::try_new(SettingsParams { + attendance_statuses: statuses_with(&["tur", "tür"]), + ..params() + }) + .is_ok() + ); + } + #[tokio::test] async fn kind_weights_resolve_by_exact_name() { let s = Settings::try_new(SettingsParams { diff --git a/src/domain/text_fold.rs b/src/domain/text_fold.rs index 2b957b2..93c1665 100644 --- a/src/domain/text_fold.rs +++ b/src/domain/text_fold.rs @@ -1,5 +1,14 @@ -//! Case- and diacritic-insensitive folding for search, shared by the needle -//! (Rust side) and the column (SurrealQL side) so the two can never disagree. +//! Two different folds, for two different jobs — never swap them: +//! +//! * [`search_fold`] / [`search_fold_sql`] are the **search** fold: +//! deliberately *destructive*, collapsing `ı ş ğ ç ö ü â î û` onto their +//! ASCII bases so a teacher on an ASCII keyboard still finds accented data. +//! * [`case_fold_tr`] is the **identity** fold: Turkish-correct case folding +//! only. It answers "are these two entries the same word?" and must never +//! conflate distinct letters (`tur` ≠ `tür`, `kir` ≠ `kır`). +//! +//! The search fold is shared by the needle (Rust side) and the column +//! (SurrealQL side) so the two can never disagree. //! //! Rust's `to_lowercase` and SurrealQL's `string::lowercase` are both //! locale-invariant: Turkish `İ` (U+0130) lowercases to `i` + U+0307 @@ -10,8 +19,9 @@ //! `ıgdır` ↔ `Iğdır`). /// Replacements applied *after* lowercasing, in order. One table, two -/// consumers ([`fold`] and [`fold_sql`]): the needle and the column are folded -/// by the same rules by construction, which is the whole point. +/// consumers ([`search_fold`] and [`search_fold_sql`]): the needle and the +/// column are folded by the same rules by construction, which is the whole +/// point. const REPLACEMENTS: &[(&str, &str)] = &[ ("\u{307}", ""), // combining dot above, left behind by İ → i̇ ("ı", "i"), @@ -25,8 +35,10 @@ const REPLACEMENTS: &[(&str, &str)] = &[ ("û", "u"), ]; -/// Fold a search needle (or any Rust-side string) for comparison. -pub fn fold(text: &str) -> String { +/// Fold a search needle (or any Rust-side string) for comparison. **Search +/// only** — this is lossy, `tür` and `tur` both fold to `tur`. For "is this +/// the same word?" use [`case_fold_tr`]. +pub fn search_fold(text: &str) -> String { let mut folded = text.to_lowercase(); for (from, to) in REPLACEMENTS { folded = folded.replace(from, to); @@ -37,7 +49,7 @@ pub fn fold(text: &str) -> String { /// The same folding as a SurrealQL expression over `column`, for use inside a /// `WHERE`. `column` is always a literal field name we wrote — never user /// input. -pub fn fold_sql(column: &str) -> String { +pub fn search_fold_sql(column: &str) -> String { let mut expr = format!("string::lowercase({column})"); for (from, to) in REPLACEMENTS { expr = format!("string::replace({expr}, '{from}', '{to}')"); @@ -45,20 +57,77 @@ pub fn fold_sql(column: &str) -> String { expr } +/// Case-fold under the **Turkish** casing rule, for identity comparisons +/// (list dedup). Only the two dotted/dotless pairs are folded together — +/// `i` ↔ `İ` and `ı` ↔ `I` — so `TÜR` and `tür` are one word while `tur` and +/// `tür` stay two. Never use this for search: it will not match an ASCII +/// spelling of an accented word (that is [`search_fold`]'s job). +pub fn case_fold_tr(text: &str) -> String { + let mut folded = String::with_capacity(text.len()); + for ch in text.chars() { + match ch { + // Rust would lowercase these locale-invariantly: `İ` → `i` plus a + // combining dot, and `I` → `i` (the *dotted* i, wrong letter). + 'İ' => folded.push('i'), + 'I' => folded.push('ı'), + _ => folded.extend(ch.to_lowercase()), + } + } + // A decomposed `İ` (`i` + combining dot above) is the same letter as `i`. + folded.replace("i\u{307}", "i") +} + #[cfg(test)] mod tests { use super::*; #[test] fn folds_turkish_casing_both_ways() { - assert_eq!(fold("İSTANBUL"), "istanbul"); - assert_eq!(fold("istanbul"), "istanbul"); - assert_eq!(fold("İstanbul"), "istanbul"); - assert_eq!(fold("ISTANBUL"), "istanbul"); - assert_eq!(fold("ıstanbul"), "istanbul"); - assert_eq!(fold("Iğdır"), "igdir"); - assert_eq!(fold("ÇÖZÜM"), "cozum"); - assert_eq!(fold("Şekil"), "sekil"); + assert_eq!(search_fold("İSTANBUL"), "istanbul"); + assert_eq!(search_fold("istanbul"), "istanbul"); + assert_eq!(search_fold("İstanbul"), "istanbul"); + assert_eq!(search_fold("ISTANBUL"), "istanbul"); + assert_eq!(search_fold("ıstanbul"), "istanbul"); + assert_eq!(search_fold("Iğdır"), "igdir"); + assert_eq!(search_fold("ÇÖZÜM"), "cozum"); + assert_eq!(search_fold("Şekil"), "sekil"); + } + + /// The identity fold folds case (Turkish rules) and *nothing else* — the + /// truth table the settings dedup depends on. + #[test] + fn case_fold_tr_folds_case_but_not_letters() { + // Same word, different case. + for (upper, lower) in [ + ("TÜR", "tür"), + ("KIR", "kır"), + ("İSTANBUL", "istanbul"), + ("ISPARTA", "ısparta"), + ("İZİN", "izin"), + ("SINAV", "sınav"), + ("LAB", "lab"), + ] { + assert_eq!( + case_fold_tr(upper), + case_fold_tr(lower), + "{upper} and {lower} are the same word" + ); + } + // Distinct words the destructive search fold wrongly collapsed. + for (a, b) in [("tur", "tür"), ("kir", "kır"), ("sıra", "sira")] { + assert_ne!( + case_fold_tr(a), + case_fold_tr(b), + "{a} and {b} are different words" + ); + assert_eq!( + search_fold(a), + search_fold(b), + "search fold still collapses {a}/{b}" + ); + } + // Decomposed `İ` (i + combining dot) is still plain `i`. + assert_eq!(case_fold_tr("i\u{307}zin"), "izin"); } /// The SQL side must fold a literal exactly like the Rust side does, or the @@ -68,14 +137,14 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); for sample in ["İSTANBUL", "Iğdır", "ÇÖZÜM", "istanbul"] { let mut result = db - .query(format!("RETURN {};", fold_sql("$text"))) + .query(format!("RETURN {};", search_fold_sql("$text"))) .bind(("text", sample.to_string())) .await .unwrap() .check() .unwrap(); let got = result.take::>(0).unwrap().unwrap(); - assert_eq!(got, fold(sample), "sql fold disagrees for {sample}"); + assert_eq!(got, search_fold(sample), "sql fold disagrees for {sample}"); } } } diff --git a/src/domain/user.rs b/src/domain/user.rs index a03b5f6..6383018 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -9,7 +9,7 @@ use crate::database::{Database, USER_TABLE}; use crate::domain::preferences::{Language, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; -use crate::domain::text_fold::{fold, fold_sql}; +use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_password, validate_username}; @@ -341,12 +341,12 @@ impl User { role: Option, db: &Database, ) -> Result, AppError> { - let needle = fold(query.trim()); + let needle = search_fold(query.trim()); let text_clause = format!( "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", - fold_sql("username"), - fold_sql("name ?? ''"), - fold_sql("surname ?? ''"), + search_fold_sql("username"), + search_fold_sql("name ?? ''"), + search_fold_sql("surname ?? ''"), ); let mut clauses = Vec::new(); if !needle.is_empty() {