prax-query 0.9.7

Type-safe query builder for the Prax ORM
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Connection and pool options.

use std::collections::HashMap;
use std::time::Duration;

/// SSL/TLS mode for connections.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SslMode {
    /// Disable SSL.
    Disable,
    /// Allow SSL but don't require it.
    Allow,
    /// Prefer SSL but allow non-SSL.
    #[default]
    Prefer,
    /// Require SSL.
    Require,
    /// Require SSL and verify the server certificate.
    VerifyCa,
    /// Require SSL and verify the server certificate and hostname.
    VerifyFull,
}

impl SslMode {
    /// Parse from string.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "disable" | "false" | "0" => Some(Self::Disable),
            "allow" => Some(Self::Allow),
            "prefer" => Some(Self::Prefer),
            "require" | "true" | "1" => Some(Self::Require),
            "verify-ca" | "verify_ca" => Some(Self::VerifyCa),
            "verify-full" | "verify_full" => Some(Self::VerifyFull),
            _ => None,
        }
    }

    /// Convert to string.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Disable => "disable",
            Self::Allow => "allow",
            Self::Prefer => "prefer",
            Self::Require => "require",
            Self::VerifyCa => "verify-ca",
            Self::VerifyFull => "verify-full",
        }
    }
}

/// SSL/TLS configuration.
#[derive(Debug, Clone, Default)]
pub struct SslConfig {
    /// SSL mode.
    pub mode: SslMode,
    /// Path to CA certificate.
    pub ca_cert: Option<String>,
    /// Path to client certificate.
    pub client_cert: Option<String>,
    /// Path to client key.
    pub client_key: Option<String>,
    /// Server name for SNI.
    pub server_name: Option<String>,
}

impl SslConfig {
    /// Create a new SSL config.
    pub fn new(mode: SslMode) -> Self {
        Self {
            mode,
            ..Default::default()
        }
    }

    /// Require SSL.
    pub fn require() -> Self {
        Self::new(SslMode::Require)
    }

    /// Set CA certificate path.
    pub fn with_ca_cert(mut self, path: impl Into<String>) -> Self {
        self.ca_cert = Some(path.into());
        self
    }

    /// Set client certificate path.
    pub fn with_client_cert(mut self, path: impl Into<String>) -> Self {
        self.client_cert = Some(path.into());
        self
    }

    /// Set client key path.
    pub fn with_client_key(mut self, path: impl Into<String>) -> Self {
        self.client_key = Some(path.into());
        self
    }
}

/// Common connection options.
#[derive(Debug, Clone)]
pub struct ConnectionOptions {
    /// Connection timeout.
    pub connect_timeout: Duration,
    /// Read timeout.
    pub read_timeout: Option<Duration>,
    /// Write timeout.
    pub write_timeout: Option<Duration>,
    /// SSL configuration.
    pub ssl: SslConfig,
    /// Application name.
    pub application_name: Option<String>,
    /// Schema/database to use after connecting.
    pub schema: Option<String>,
    /// Additional options as key-value pairs.
    pub extra: HashMap<String, String>,
}

impl Default for ConnectionOptions {
    fn default() -> Self {
        Self {
            connect_timeout: Duration::from_secs(30),
            read_timeout: None,
            write_timeout: None,
            ssl: SslConfig::default(),
            application_name: None,
            schema: None,
            extra: HashMap::new(),
        }
    }
}

impl ConnectionOptions {
    /// Create new connection options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set connection timeout.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Set read timeout.
    pub fn read_timeout(mut self, timeout: Duration) -> Self {
        self.read_timeout = Some(timeout);
        self
    }

    /// Set write timeout.
    pub fn write_timeout(mut self, timeout: Duration) -> Self {
        self.write_timeout = Some(timeout);
        self
    }

    /// Set SSL mode.
    pub fn ssl_mode(mut self, mode: SslMode) -> Self {
        self.ssl.mode = mode;
        self
    }

    /// Set SSL configuration.
    pub fn ssl(mut self, config: SslConfig) -> Self {
        self.ssl = config;
        self
    }

    /// Set application name.
    pub fn application_name(mut self, name: impl Into<String>) -> Self {
        self.application_name = Some(name.into());
        self
    }

    /// Set schema.
    pub fn schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Add extra option.
    pub fn option(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.insert(key.into(), value.into());
        self
    }

    /// Parse options from URL query parameters.
    pub fn from_params(params: &HashMap<String, String>) -> Self {
        let mut opts = Self::default();

        if let Some(timeout) = params.get("connect_timeout")
            && let Ok(secs) = timeout.parse::<u64>()
        {
            opts.connect_timeout = Duration::from_secs(secs);
        }

        if let Some(timeout) = params.get("read_timeout")
            && let Ok(secs) = timeout.parse::<u64>()
        {
            opts.read_timeout = Some(Duration::from_secs(secs));
        }

        if let Some(timeout) = params.get("write_timeout")
            && let Ok(secs) = timeout.parse::<u64>()
        {
            opts.write_timeout = Some(Duration::from_secs(secs));
        }

        if let Some(ssl) = params.get("sslmode").or_else(|| params.get("ssl"))
            && let Some(mode) = SslMode::parse(ssl)
        {
            opts.ssl.mode = mode;
        }

        if let Some(name) = params.get("application_name") {
            opts.application_name = Some(name.clone());
        }

        if let Some(schema) = params.get("schema").or_else(|| params.get("search_path")) {
            opts.schema = Some(schema.clone());
        }

        // Copy remaining params as extra options
        for (key, value) in params {
            if !matches!(
                key.as_str(),
                "connect_timeout"
                    | "read_timeout"
                    | "write_timeout"
                    | "sslmode"
                    | "ssl"
                    | "application_name"
                    | "schema"
                    | "search_path"
            ) {
                opts.extra.insert(key.clone(), value.clone());
            }
        }

        opts
    }
}

/// Pool options.
#[derive(Debug, Clone)]
pub struct PoolOptions {
    /// Maximum number of connections.
    pub max_connections: u32,
    /// Minimum number of connections to keep idle.
    pub min_connections: u32,
    /// Maximum time to wait for a connection.
    pub acquire_timeout: Duration,
    /// Maximum idle time before closing a connection.
    pub idle_timeout: Option<Duration>,
    /// Maximum lifetime of a connection.
    pub max_lifetime: Option<Duration>,
    /// Test connections before returning them.
    pub test_before_acquire: bool,
}

impl Default for PoolOptions {
    fn default() -> Self {
        Self {
            max_connections: 10,
            min_connections: 1,
            acquire_timeout: Duration::from_secs(30),
            idle_timeout: Some(Duration::from_secs(600)),
            max_lifetime: Some(Duration::from_secs(1800)),
            test_before_acquire: true,
        }
    }
}

impl PoolOptions {
    /// Create new pool options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set max connections.
    pub fn max_connections(mut self, n: u32) -> Self {
        self.max_connections = n;
        self
    }

    /// Set min connections.
    pub fn min_connections(mut self, n: u32) -> Self {
        self.min_connections = n;
        self
    }

    /// Set acquire timeout.
    pub fn acquire_timeout(mut self, timeout: Duration) -> Self {
        self.acquire_timeout = timeout;
        self
    }

    /// Set idle timeout.
    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
        self.idle_timeout = Some(timeout);
        self
    }

    /// Disable idle timeout.
    pub fn no_idle_timeout(mut self) -> Self {
        self.idle_timeout = None;
        self
    }

    /// Set max lifetime.
    pub fn max_lifetime(mut self, lifetime: Duration) -> Self {
        self.max_lifetime = Some(lifetime);
        self
    }

    /// Disable max lifetime.
    pub fn no_max_lifetime(mut self) -> Self {
        self.max_lifetime = None;
        self
    }

    /// Enable/disable test before acquire.
    pub fn test_before_acquire(mut self, enabled: bool) -> Self {
        self.test_before_acquire = enabled;
        self
    }
}

/// PostgreSQL-specific options.
#[derive(Debug, Clone, Default)]
pub struct PostgresOptions {
    /// Statement cache capacity.
    pub statement_cache_capacity: usize,
    /// Enable prepared statements.
    pub prepared_statements: bool,
    /// Channel binding mode.
    pub channel_binding: Option<String>,
    /// Target session attributes.
    pub target_session_attrs: Option<String>,
}

impl PostgresOptions {
    /// Create new PostgreSQL options.
    pub fn new() -> Self {
        Self {
            statement_cache_capacity: 100,
            prepared_statements: true,
            channel_binding: None,
            target_session_attrs: None,
        }
    }

    /// Set statement cache capacity.
    pub fn statement_cache(mut self, capacity: usize) -> Self {
        self.statement_cache_capacity = capacity;
        self
    }

    /// Enable/disable prepared statements.
    pub fn prepared_statements(mut self, enabled: bool) -> Self {
        self.prepared_statements = enabled;
        self
    }
}

/// MySQL-specific options.
#[derive(Debug, Clone, Default)]
pub struct MySqlOptions {
    /// Enable compression.
    pub compression: bool,
    /// Character set.
    pub charset: Option<String>,
    /// Collation.
    pub collation: Option<String>,
    /// SQL mode.
    pub sql_mode: Option<String>,
    /// Timezone.
    pub timezone: Option<String>,
}

impl MySqlOptions {
    /// Create new MySQL options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable compression.
    pub fn compression(mut self, enabled: bool) -> Self {
        self.compression = enabled;
        self
    }

    /// Set character set.
    pub fn charset(mut self, charset: impl Into<String>) -> Self {
        self.charset = Some(charset.into());
        self
    }

    /// Set SQL mode.
    pub fn sql_mode(mut self, mode: impl Into<String>) -> Self {
        self.sql_mode = Some(mode.into());
        self
    }
}

/// SQLite-specific options.
#[derive(Debug, Clone)]
pub struct SqliteOptions {
    /// Journal mode.
    pub journal_mode: SqliteJournalMode,
    /// Synchronous mode.
    pub synchronous: SqliteSynchronous,
    /// Foreign keys enforcement.
    pub foreign_keys: bool,
    /// Busy timeout in milliseconds.
    pub busy_timeout: u32,
    /// Cache size in pages (negative for KB).
    pub cache_size: i32,
}

impl Default for SqliteOptions {
    fn default() -> Self {
        Self {
            journal_mode: SqliteJournalMode::Wal,
            synchronous: SqliteSynchronous::Normal,
            foreign_keys: true,
            busy_timeout: 5000,
            cache_size: -2000, // 2MB
        }
    }
}

impl SqliteOptions {
    /// Create new SQLite options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set journal mode.
    pub fn journal_mode(mut self, mode: SqliteJournalMode) -> Self {
        self.journal_mode = mode;
        self
    }

    /// Set synchronous mode.
    pub fn synchronous(mut self, mode: SqliteSynchronous) -> Self {
        self.synchronous = mode;
        self
    }

    /// Enable/disable foreign keys.
    pub fn foreign_keys(mut self, enabled: bool) -> Self {
        self.foreign_keys = enabled;
        self
    }

    /// Set busy timeout in milliseconds.
    pub fn busy_timeout(mut self, ms: u32) -> Self {
        self.busy_timeout = ms;
        self
    }

    /// Generate PRAGMA statements.
    pub fn to_pragmas(&self) -> Vec<String> {
        vec![
            format!("PRAGMA journal_mode = {};", self.journal_mode.as_str()),
            format!("PRAGMA synchronous = {};", self.synchronous.as_str()),
            format!(
                "PRAGMA foreign_keys = {};",
                if self.foreign_keys { "ON" } else { "OFF" }
            ),
            format!("PRAGMA busy_timeout = {};", self.busy_timeout),
            format!("PRAGMA cache_size = {};", self.cache_size),
        ]
    }
}

/// SQLite journal mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SqliteJournalMode {
    /// Delete journal after transaction.
    Delete,
    /// Truncate journal.
    Truncate,
    /// Persist journal.
    Persist,
    /// In-memory journal.
    Memory,
    /// Write-ahead logging (recommended).
    #[default]
    Wal,
    /// Disable journaling.
    Off,
}

impl SqliteJournalMode {
    /// Get the SQL string.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Delete => "DELETE",
            Self::Truncate => "TRUNCATE",
            Self::Persist => "PERSIST",
            Self::Memory => "MEMORY",
            Self::Wal => "WAL",
            Self::Off => "OFF",
        }
    }
}

/// SQLite synchronous mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SqliteSynchronous {
    /// No synchronization.
    Off,
    /// Normal synchronization.
    #[default]
    Normal,
    /// Full synchronization.
    Full,
    /// Extra synchronization.
    Extra,
}

impl SqliteSynchronous {
    /// Get the SQL string.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Off => "OFF",
            Self::Normal => "NORMAL",
            Self::Full => "FULL",
            Self::Extra => "EXTRA",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ssl_mode_parse() {
        assert_eq!(SslMode::parse("disable"), Some(SslMode::Disable));
        assert_eq!(SslMode::parse("require"), Some(SslMode::Require));
        assert_eq!(SslMode::parse("verify-full"), Some(SslMode::VerifyFull));
        assert_eq!(SslMode::parse("invalid"), None);
    }

    #[test]
    fn test_connection_options_builder() {
        let opts = ConnectionOptions::new()
            .connect_timeout(Duration::from_secs(10))
            .ssl_mode(SslMode::Require)
            .application_name("test-app");

        assert_eq!(opts.connect_timeout, Duration::from_secs(10));
        assert_eq!(opts.ssl.mode, SslMode::Require);
        assert_eq!(opts.application_name, Some("test-app".to_string()));
    }

    #[test]
    fn test_pool_options_builder() {
        let opts = PoolOptions::new()
            .max_connections(20)
            .min_connections(5)
            .no_idle_timeout();

        assert_eq!(opts.max_connections, 20);
        assert_eq!(opts.min_connections, 5);
        assert_eq!(opts.idle_timeout, None);
    }

    #[test]
    fn test_sqlite_options_pragmas() {
        let opts = SqliteOptions::new()
            .journal_mode(SqliteJournalMode::Wal)
            .foreign_keys(true);

        let pragmas = opts.to_pragmas();
        assert!(pragmas.iter().any(|p| p.contains("journal_mode = WAL")));
        assert!(pragmas.iter().any(|p| p.contains("foreign_keys = ON")));
    }

    #[test]
    fn test_options_from_params() {
        let mut params = HashMap::new();
        params.insert("connect_timeout".to_string(), "10".to_string());
        params.insert("sslmode".to_string(), "require".to_string());
        params.insert("application_name".to_string(), "myapp".to_string());

        let opts = ConnectionOptions::from_params(&params);
        assert_eq!(opts.connect_timeout, Duration::from_secs(10));
        assert_eq!(opts.ssl.mode, SslMode::Require);
        assert_eq!(opts.application_name, Some("myapp".to_string()));
    }
}