fraiseql-db 2.2.0

Database abstraction layer for FraiseQL v2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Database-specific collation mapping.
//!
//! Maps user locales to database-specific collation strings, adapting to each
//! database's collation capabilities.

use fraiseql_error::{FraiseQLError, Result};

use crate::{collation_config::CollationConfig, types::DatabaseType};

/// Maps user locales to database-specific collation strings.
///
/// The mapper takes a global `CollationConfig` and database type, then translates
/// user locales (e.g., "fr-FR") into the appropriate database-specific collation
/// format (e.g., "fr-FR-x-icu" for PostgreSQL with ICU).
///
/// # Examples
///
/// ```
/// use fraiseql_db::CollationConfig;
/// use fraiseql_db::{DatabaseType, collation::CollationMapper};
///
/// // PostgreSQL with ICU
/// let config = CollationConfig::default();
/// let mapper = CollationMapper::new(config.clone(), DatabaseType::PostgreSQL);
/// assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("fr-FR-x-icu".to_string()));
///
/// // MySQL (general collation, not locale-specific)
/// let mapper = CollationMapper::new(config, DatabaseType::MySQL);
/// assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("utf8mb4_unicode_ci".to_string()));
/// ```
pub struct CollationMapper {
    config:        CollationConfig,
    database_type: DatabaseType,
}

impl CollationMapper {
    /// Create a new collation mapper.
    ///
    /// # Arguments
    ///
    /// * `config` - Global collation configuration
    /// * `database_type` - Target database type
    #[must_use]
    pub const fn new(config: CollationConfig, database_type: DatabaseType) -> Self {
        Self {
            config,
            database_type,
        }
    }

    /// Map user locale to database-specific collation string.
    ///
    /// # Arguments
    ///
    /// * `locale` - User locale (e.g., "fr-FR", "ja-JP")
    ///
    /// # Returns
    ///
    /// - `Ok(Some(collation))` - Database-specific collation string
    /// - `Ok(None)` - Use database default (no COLLATE clause)
    /// - `Err(_)` - Invalid locale when strategy is `Error`
    ///
    /// # Errors
    ///
    /// Returns `FraiseQLError::Validation` if locale is not in allowed list
    /// and `on_invalid_locale` is set to `Error`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fraiseql_db::CollationConfig;
    /// use fraiseql_db::{DatabaseType, collation::CollationMapper};
    ///
    /// let config = CollationConfig::default();
    /// let mapper = CollationMapper::new(config, DatabaseType::PostgreSQL);
    ///
    /// // Valid locale
    /// let collation = mapper.map_locale("fr-FR").unwrap();
    /// assert_eq!(collation, Some("fr-FR-x-icu".to_string()));
    ///
    /// // Invalid locale (not in allowed list)
    /// let result = mapper.map_locale("invalid");
    /// assert!(result.is_ok(), "utf8 is a valid collation: {result:?}");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`FraiseQLError::Validation`] if `locale` is not in the allowed list
    /// and the configured `InvalidLocaleStrategy` is `Reject`.
    pub fn map_locale(&self, locale: &str) -> Result<Option<String>> {
        if !self.config.enabled {
            return Ok(None);
        }

        // Check if locale is allowed
        if !self.config.allowed_locales.contains(&locale.to_string()) {
            return self.handle_invalid_locale();
        }

        match self.database_type {
            DatabaseType::PostgreSQL => Ok(self.map_postgres(locale)),
            DatabaseType::MySQL => Ok(self.map_mysql(locale)),
            DatabaseType::SQLite => Ok(self.map_sqlite(locale)),
            DatabaseType::SQLServer => Ok(self.map_sqlserver(locale)),
        }
    }

    /// Map locale for PostgreSQL.
    ///
    /// Supports both ICU and libc collations:
    /// - ICU: "fr-FR-x-icu" (recommended, Unicode-aware)
    /// - libc: "fr_FR.UTF-8" (system-dependent)
    fn map_postgres(&self, locale: &str) -> Option<String> {
        if let Some(overrides) = &self.config.database_overrides {
            if let Some(pg_config) = &overrides.postgres {
                if pg_config.use_icu {
                    return Some(format!("{locale}-x-icu"));
                }
                // libc format: en_US.UTF-8
                let libc_locale = locale.replace('-', "_");
                return Some(format!("{libc_locale}.UTF-8"));
            }
        }

        // Default: ICU collation
        Some(format!("{locale}-x-icu"))
    }

    /// Map locale for MySQL.
    ///
    /// MySQL collations are charset-based, not locale-specific.
    /// All locales map to the same general-purpose collation.
    fn map_mysql(&self, _locale: &str) -> Option<String> {
        if let Some(overrides) = &self.config.database_overrides {
            if let Some(mysql_config) = &overrides.mysql {
                return Some(format!("{}{}", mysql_config.charset, mysql_config.suffix));
            }
        }

        // Default: utf8mb4_unicode_ci (supports all languages)
        Some("utf8mb4_unicode_ci".to_string())
    }

    /// Map locale for SQLite.
    ///
    /// SQLite has very limited collation support. Only NOCASE is built-in
    /// for case-insensitive sorting.
    fn map_sqlite(&self, _locale: &str) -> Option<String> {
        if let Some(overrides) = &self.config.database_overrides {
            if let Some(sqlite_config) = &overrides.sqlite {
                return if sqlite_config.use_nocase {
                    Some("NOCASE".to_string())
                } else {
                    None
                };
            }
        }

        // Default: NOCASE
        Some("NOCASE".to_string())
    }

    /// Map locale for SQL Server.
    ///
    /// Maps common locales to SQL Server language-specific collations.
    fn map_sqlserver(&self, locale: &str) -> Option<String> {
        // Map common locales to SQL Server collations
        let collation = match locale {
            "en-US" | "en-GB" | "en-CA" | "en-AU" => "Latin1_General_100_CI_AI_SC_UTF8",
            "fr-FR" | "fr-CA" => "French_100_CI_AI",
            "de-DE" | "de-AT" | "de-CH" => "German_PhoneBook_100_CI_AI",
            "es-ES" | "es-MX" => "Modern_Spanish_100_CI_AI",
            "ja-JP" => "Japanese_XJIS_100_CI_AI",
            "zh-CN" => "Chinese_PRC_100_CI_AI",
            "pt-BR" => "Latin1_General_100_CI_AI_SC_UTF8",
            "it-IT" => "Latin1_General_100_CI_AI_SC_UTF8",
            _ => "Latin1_General_100_CI_AI_SC_UTF8", // Default
        };

        Some(collation.to_string())
    }

    /// Handle invalid locale based on configuration strategy.
    fn handle_invalid_locale(&self) -> Result<Option<String>> {
        use crate::collation_config::InvalidLocaleStrategy;

        match self.config.on_invalid_locale {
            InvalidLocaleStrategy::Fallback => self.map_locale(&self.config.fallback_locale),
            InvalidLocaleStrategy::DatabaseDefault => Ok(None),
            InvalidLocaleStrategy::Error => Err(FraiseQLError::Validation {
                message: "Invalid locale: not in allowed list".to_string(),
                path:    None,
            }),
        }
    }

    /// Get the database type this mapper is configured for.
    #[must_use]
    pub const fn database_type(&self) -> DatabaseType {
        self.database_type
    }

    /// Check if collation is enabled.
    #[must_use]
    pub const fn is_enabled(&self) -> bool {
        self.config.enabled
    }
}

/// Database collation capabilities.
///
/// Provides information about what collation features each database supports.
pub struct CollationCapabilities;

impl CollationCapabilities {
    /// Check if database supports locale-specific collations.
    ///
    /// - PostgreSQL: ✅ Full support via ICU or libc
    /// - MySQL: ❌ Only charset-based collations
    /// - SQLite: ❌ Limited to NOCASE or custom functions
    /// - SQL Server: ✅ Language-specific collations
    #[must_use]
    pub const fn supports_locale_collation(db_type: DatabaseType) -> bool {
        matches!(db_type, DatabaseType::PostgreSQL | DatabaseType::SQLServer)
    }

    /// Check if database requires custom collation registration.
    ///
    /// SQLite requires custom collation functions to be registered for
    /// locale-aware sorting beyond NOCASE.
    #[must_use]
    pub const fn requires_custom_collation(db_type: DatabaseType) -> bool {
        matches!(db_type, DatabaseType::SQLite)
    }

    /// Get collation strategy description for database.
    #[must_use]
    pub const fn strategy(db_type: DatabaseType) -> &'static str {
        match db_type {
            DatabaseType::PostgreSQL => "ICU collations (locale-specific)",
            DatabaseType::MySQL => "UTF8MB4 collations (general)",
            DatabaseType::SQLite => "NOCASE (limited)",
            DatabaseType::SQLServer => "Language-specific collations",
        }
    }

    /// Get recommended collation provider for database.
    #[must_use]
    pub const fn recommended_provider(db_type: DatabaseType) -> Option<&'static str> {
        match db_type {
            DatabaseType::PostgreSQL => Some("icu"),
            DatabaseType::MySQL => Some("utf8mb4_unicode_ci"),
            DatabaseType::SQLite => Some("NOCASE"),
            DatabaseType::SQLServer => Some("Latin1_General_100_CI_AI_SC_UTF8"),
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
mod tests {
    use super::*;
    use crate::collation_config::{
        DatabaseCollationOverrides, InvalidLocaleStrategy, MySqlCollationConfig,
        PostgresCollationConfig, SqliteCollationConfig,
    };

    fn test_config() -> CollationConfig {
        CollationConfig {
            enabled:            true,
            fallback_locale:    "en-US".to_string(),
            allowed_locales:    vec!["en-US".into(), "fr-FR".into(), "ja-JP".into()],
            on_invalid_locale:  InvalidLocaleStrategy::Fallback,
            database_overrides: None,
        }
    }

    #[test]
    fn test_postgres_icu_collation() {
        let config = test_config();
        let mapper = CollationMapper::new(config, DatabaseType::PostgreSQL);

        assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("fr-FR-x-icu".to_string()));
        assert_eq!(mapper.map_locale("ja-JP").unwrap(), Some("ja-JP-x-icu".to_string()));
    }

    #[test]
    fn test_postgres_libc_collation() {
        let mut config = test_config();
        config.database_overrides = Some(DatabaseCollationOverrides {
            postgres:  Some(PostgresCollationConfig {
                use_icu:  false,
                provider: "libc".to_string(),
            }),
            mysql:     None,
            sqlite:    None,
            sqlserver: None,
        });

        let mapper = CollationMapper::new(config, DatabaseType::PostgreSQL);

        assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("fr_FR.UTF-8".to_string()));
        assert_eq!(mapper.map_locale("en-US").unwrap(), Some("en_US.UTF-8".to_string()));
    }

    #[test]
    fn test_mysql_collation() {
        let config = test_config();
        let mapper = CollationMapper::new(config, DatabaseType::MySQL);

        // All locales map to same charset-based collation
        assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("utf8mb4_unicode_ci".to_string()));
        assert_eq!(mapper.map_locale("ja-JP").unwrap(), Some("utf8mb4_unicode_ci".to_string()));
    }

    #[test]
    fn test_mysql_custom_collation() {
        let mut config = test_config();
        config.database_overrides = Some(DatabaseCollationOverrides {
            postgres:  None,
            mysql:     Some(MySqlCollationConfig {
                charset: "utf8mb4".to_string(),
                suffix:  "_0900_ai_ci".to_string(),
            }),
            sqlite:    None,
            sqlserver: None,
        });

        let mapper = CollationMapper::new(config, DatabaseType::MySQL);

        assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("utf8mb4_0900_ai_ci".to_string()));
    }

    #[test]
    fn test_sqlite_collation() {
        let config = test_config();
        let mapper = CollationMapper::new(config, DatabaseType::SQLite);

        assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("NOCASE".to_string()));
    }

    #[test]
    fn test_sqlite_disabled_nocase() {
        let mut config = test_config();
        config.database_overrides = Some(DatabaseCollationOverrides {
            postgres:  None,
            mysql:     None,
            sqlite:    Some(SqliteCollationConfig { use_nocase: false }),
            sqlserver: None,
        });

        let mapper = CollationMapper::new(config, DatabaseType::SQLite);

        assert_eq!(mapper.map_locale("fr-FR").unwrap(), None);
    }

    #[test]
    fn test_sqlserver_collation() {
        let config = test_config();
        let mapper = CollationMapper::new(config, DatabaseType::SQLServer);

        assert_eq!(mapper.map_locale("fr-FR").unwrap(), Some("French_100_CI_AI".to_string()));
        assert_eq!(
            mapper.map_locale("ja-JP").unwrap(),
            Some("Japanese_XJIS_100_CI_AI".to_string())
        );
    }

    #[test]
    fn test_invalid_locale_fallback() {
        let config = test_config();
        let mapper = CollationMapper::new(config, DatabaseType::PostgreSQL);

        // Invalid locale should use fallback
        let result = mapper.map_locale("invalid-locale").unwrap();
        assert_eq!(result, Some("en-US-x-icu".to_string()));
    }

    #[test]
    fn test_invalid_locale_database_default() {
        let mut config = test_config();
        config.on_invalid_locale = InvalidLocaleStrategy::DatabaseDefault;
        let mapper = CollationMapper::new(config, DatabaseType::PostgreSQL);

        // Invalid locale should return None (use database default)
        let result = mapper.map_locale("invalid-locale").unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_invalid_locale_error() {
        let mut config = test_config();
        config.on_invalid_locale = InvalidLocaleStrategy::Error;
        let mapper = CollationMapper::new(config, DatabaseType::PostgreSQL);

        // Invalid locale should return error
        let result = mapper.map_locale("invalid-locale");
        assert!(
            result.is_err(),
            "expected Err for invalid locale with Error strategy, got: {result:?}"
        );
    }

    #[test]
    fn test_disabled_collation() {
        let mut config = test_config();
        config.enabled = false;
        let mapper = CollationMapper::new(config, DatabaseType::PostgreSQL);

        // Should always return None when disabled
        assert_eq!(mapper.map_locale("fr-FR").unwrap(), None);
        assert_eq!(mapper.map_locale("en-US").unwrap(), None);
    }

    #[test]
    fn test_capabilities_locale_support() {
        assert!(CollationCapabilities::supports_locale_collation(DatabaseType::PostgreSQL));
        assert!(CollationCapabilities::supports_locale_collation(DatabaseType::SQLServer));
        assert!(!CollationCapabilities::supports_locale_collation(DatabaseType::MySQL));
        assert!(!CollationCapabilities::supports_locale_collation(DatabaseType::SQLite));
    }

    #[test]
    fn test_capabilities_custom_collation() {
        assert!(CollationCapabilities::requires_custom_collation(DatabaseType::SQLite));
        assert!(!CollationCapabilities::requires_custom_collation(DatabaseType::PostgreSQL));
        assert!(!CollationCapabilities::requires_custom_collation(DatabaseType::MySQL));
        assert!(!CollationCapabilities::requires_custom_collation(DatabaseType::SQLServer));
    }

    #[test]
    fn test_capabilities_strategy() {
        assert_eq!(
            CollationCapabilities::strategy(DatabaseType::PostgreSQL),
            "ICU collations (locale-specific)"
        );
        assert_eq!(
            CollationCapabilities::strategy(DatabaseType::MySQL),
            "UTF8MB4 collations (general)"
        );
        assert_eq!(CollationCapabilities::strategy(DatabaseType::SQLite), "NOCASE (limited)");
        assert_eq!(
            CollationCapabilities::strategy(DatabaseType::SQLServer),
            "Language-specific collations"
        );
    }
}