bsql-core 0.22.1

Runtime support for bsql — compile-time safe SQL for Rust
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Test infrastructure for `#[bsql::test]`.
//!
//! Creates isolated PostgreSQL schemas per test for parallel execution.
//! Fixtures (SQL files) are applied to the schema before the test runs.
//! Schema is dropped after the test -- even on panic.

use std::sync::atomic::{AtomicU64, Ordering};

use bsql_driver_postgres::{Config, Connection};

use crate::error::{BsqlError, ConnectError};
use crate::pool::Pool;

static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Test context holding the pool and cleanup info.
/// Drops the schema on cleanup.
pub struct TestContext {
    /// The connection pool, scoped to the isolated test schema.
    pub pool: Pool,
    schema_name: String,
    db_url: String,
}

impl std::fmt::Debug for TestContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TestContext")
            .field("schema", &self.schema_name)
            .finish()
    }
}

impl Drop for TestContext {
    fn drop(&mut self) {
        // Fresh connection for cleanup (pool connection may be broken after panic).
        // Errors are intentionally ignored -- we are in a destructor.
        if let Ok(config) = Config::from_url(&self.db_url) {
            if let Ok(mut conn) = Connection::connect(&config) {
                let _ = conn.simple_query(&format!(
                    "DROP SCHEMA IF EXISTS \"{}\" CASCADE",
                    self.schema_name
                ));
            }
        }
    }
}

/// Set up an isolated test schema with fixtures.
///
/// Called by generated `#[bsql::test]` code. Not intended for direct use.
///
/// `fixtures_sql` contains compile-time embedded SQL strings from fixture files.
pub async fn setup_test_schema(fixtures_sql: &[&str]) -> Result<TestContext, BsqlError> {
    let db_url = std::env::var("BSQL_DATABASE_URL")
        .or_else(|_| std::env::var("DATABASE_URL"))
        .map_err(|_| {
            ConnectError::create("BSQL_DATABASE_URL or DATABASE_URL must be set for #[bsql::test]")
        })?;

    let schema_name = format!(
        "__bsql_test_{}_{}",
        std::process::id(),
        TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
    );

    // Setup connection: create schema, apply fixtures
    let config = Config::from_url(&db_url)
        .map_err(|e| ConnectError::create(format!("invalid database URL: {e}")))?;
    let mut conn = Connection::connect(&config)
        .map_err(|e| ConnectError::create(format!("connection failed: {e}")))?;

    // Create isolated schema
    conn.simple_query(&format!("CREATE SCHEMA \"{}\"", schema_name))
        .map_err(|e| ConnectError::create(format!("failed to create test schema: {e}")))?;

    // Set search_path to test schema (with public for extensions)
    conn.simple_query(&format!("SET search_path TO \"{}\", public", schema_name))
        .map_err(|e| ConnectError::create(format!("failed to set search_path: {e}")))?;

    // Apply fixtures in order
    for fixture_sql in fixtures_sql {
        if !fixture_sql.trim().is_empty() {
            conn.simple_query(fixture_sql)
                .map_err(|e| ConnectError::create(format!("fixture failed: {e}")))?;
        }
    }

    drop(conn); // Release setup connection

    // Build pool. Connections are lazy, so we create the pool first,
    // then immediately acquire one connection and set search_path on it.
    let pool = Pool::connect(&db_url).await?;

    // Acquire a connection and set search_path so all subsequent queries
    // in this test run against the isolated schema.
    pool.raw_execute(&format!("SET search_path TO \"{}\", public", schema_name))
        .await?;

    // Set warmup SQL so any *new* connections from this pool also get
    // the correct search_path (the pool has max_size=10 by default,
    // but for tests we typically only use 1 connection).
    let warmup_sql = format!("SET search_path TO \"{}\", public", schema_name);
    // set_warmup_sqls copies strings internally (into Box<str>), so &str
    // only needs to live for the duration of this call. No leak needed.
    pool.set_warmup_sqls([warmup_sql]);

    Ok(TestContext {
        pool,
        schema_name,
        db_url,
    })
}

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

    // ---------------------------------------------------------------
    // Schema lifecycle
    // ---------------------------------------------------------------

    #[test]
    fn schema_name_is_unique() {
        let name1 = format!(
            "__bsql_test_{}_{}",
            std::process::id(),
            TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
        );
        let name2 = format!(
            "__bsql_test_{}_{}",
            std::process::id(),
            TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
        );
        assert_ne!(name1, name2);
    }

    #[test]
    fn schema_name_contains_pid() {
        let name = format!(
            "__bsql_test_{}_{}",
            std::process::id(),
            TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
        );
        assert!(name.contains(&std::process::id().to_string()));
    }

    #[test]
    fn schema_name_starts_with_prefix() {
        let name = format!(
            "__bsql_test_{}_{}",
            std::process::id(),
            TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
        );
        assert!(name.starts_with("__bsql_test_"));
    }

    #[test]
    fn schema_names_never_collide_100_sequential() {
        let mut names = HashSet::new();
        for _ in 0..100 {
            let name = format!(
                "__bsql_test_{}_{}",
                std::process::id(),
                TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
            );
            assert!(names.insert(name.clone()), "duplicate schema name: {name}");
        }
        assert_eq!(names.len(), 100);
    }

    #[test]
    fn schema_name_is_valid_sql_identifier() {
        let name = format!(
            "__bsql_test_{}_{}",
            std::process::id(),
            TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
        );
        // Valid SQL identifier: starts with letter or underscore, then alphanumeric/underscore
        assert!(
            name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
            "schema name contains invalid chars: {name}"
        );
        assert!(
            name.starts_with('_') || name.starts_with(|c: char| c.is_ascii_alphabetic()),
            "schema name must start with letter or underscore: {name}"
        );
    }

    // ---------------------------------------------------------------
    // Counter atomicity
    // ---------------------------------------------------------------

    #[test]
    fn test_counter_is_monotonic() {
        let a = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let b = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let c = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        assert!(a < b);
        assert!(b < c);
    }

    #[test]
    fn counter_increments_atomically_across_threads() {
        use std::sync::Arc;
        let results: Arc<std::sync::Mutex<Vec<u64>>> = Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut handles = Vec::new();
        for _ in 0..10 {
            let results = Arc::clone(&results);
            handles.push(std::thread::spawn(move || {
                for _ in 0..10 {
                    let val = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
                    results.lock().unwrap().push(val);
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
        let mut vals = results.lock().unwrap().clone();
        assert_eq!(vals.len(), 100, "expected 100 counter values");
        // All values must be unique (no duplicates from racing threads)
        let set: HashSet<u64> = vals.iter().copied().collect();
        assert_eq!(
            set.len(),
            100,
            "counter values must be unique across threads"
        );
        // Sorted values must be strictly increasing
        vals.sort();
        for window in vals.windows(2) {
            assert!(window[0] < window[1], "counter must be strictly increasing");
        }
    }

    // ---------------------------------------------------------------
    // Concurrency — multiple TestContexts
    // ---------------------------------------------------------------

    #[test]
    fn multiple_schema_names_created_simultaneously_are_different() {
        // Simulate what happens when multiple tests call setup at the same instant
        let names: Vec<String> = (0..50)
            .map(|_| {
                format!(
                    "__bsql_test_{}_{}",
                    std::process::id(),
                    TEST_COUNTER.fetch_add(1, Ordering::Relaxed),
                )
            })
            .collect();
        let set: HashSet<&String> = names.iter().collect();
        assert_eq!(set.len(), names.len(), "all schema names must be unique");
    }

    // ---------------------------------------------------------------
    // Setup error paths
    // ---------------------------------------------------------------

    #[tokio::test]
    async fn missing_db_url_returns_clear_error() {
        // Temporarily unset both env vars (if set)
        let orig_bsql = std::env::var("BSQL_DATABASE_URL").ok();
        let orig_db = std::env::var("DATABASE_URL").ok();
        std::env::remove_var("BSQL_DATABASE_URL");
        std::env::remove_var("DATABASE_URL");

        let result = setup_test_schema(&[]).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("BSQL_DATABASE_URL") && msg.contains("DATABASE_URL"),
            "error should mention both env vars, got: {msg}"
        );

        // Restore
        if let Some(v) = orig_bsql {
            std::env::set_var("BSQL_DATABASE_URL", v);
        }
        if let Some(v) = orig_db {
            std::env::set_var("DATABASE_URL", v);
        }
    }

    #[tokio::test]
    async fn missing_bsql_database_url_falls_back_to_database_url() {
        let orig_bsql = std::env::var("BSQL_DATABASE_URL").ok();
        let orig_db = std::env::var("DATABASE_URL").ok();
        std::env::remove_var("BSQL_DATABASE_URL");
        // Set DATABASE_URL to something invalid so we get past env-check but fail on connect
        std::env::set_var("DATABASE_URL", "not-a-url");

        let result = setup_test_schema(&[]).await;
        // Should fail on URL parse, not on missing env var
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("invalid database URL"),
            "should fail on URL parse after falling back to DATABASE_URL, got: {msg}"
        );

        // Restore
        std::env::remove_var("DATABASE_URL");
        if let Some(v) = orig_bsql {
            std::env::set_var("BSQL_DATABASE_URL", v);
        }
        if let Some(v) = orig_db {
            std::env::set_var("DATABASE_URL", v);
        }
    }

    #[tokio::test]
    async fn invalid_db_url_returns_clear_error() {
        let orig_bsql = std::env::var("BSQL_DATABASE_URL").ok();
        let orig_db = std::env::var("DATABASE_URL").ok();
        std::env::set_var("BSQL_DATABASE_URL", "not-a-valid-url");
        std::env::remove_var("DATABASE_URL");

        let result = setup_test_schema(&[]).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("invalid database URL"),
            "error should mention invalid URL, got: {msg}"
        );

        // Restore
        std::env::remove_var("BSQL_DATABASE_URL");
        if let Some(v) = orig_bsql {
            std::env::set_var("BSQL_DATABASE_URL", v);
        }
        if let Some(v) = orig_db {
            std::env::set_var("DATABASE_URL", v);
        }
    }

    #[tokio::test]
    async fn invalid_db_url_not_postgres_scheme() {
        let orig_bsql = std::env::var("BSQL_DATABASE_URL").ok();
        let orig_db = std::env::var("DATABASE_URL").ok();
        std::env::set_var("BSQL_DATABASE_URL", "mysql://user:pass@localhost/db");
        std::env::remove_var("DATABASE_URL");

        let result = setup_test_schema(&[]).await;
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("invalid database URL"),
            "non-postgres scheme should fail with clear error, got: {msg}"
        );

        std::env::remove_var("BSQL_DATABASE_URL");
        if let Some(v) = orig_bsql {
            std::env::set_var("BSQL_DATABASE_URL", v);
        }
        if let Some(v) = orig_db {
            std::env::set_var("DATABASE_URL", v);
        }
    }

    #[test]
    fn connection_refused_unreachable_host() {
        // Test the connection-refused path directly, bypassing env-var setup
        // to avoid races with other concurrent async tests that manipulate env.
        let url = "postgres://user:pass@127.0.0.1:1/testdb";
        let config = Config::from_url(url).expect("URL should parse");
        let conn_result = Connection::connect(&config);
        assert!(conn_result.is_err(), "connection to port 1 should fail");
        // Verify the error maps to a ConnectError with "connection failed" message
        // (this is the exact error path that setup_test_schema takes)
        let err = ConnectError::create(format!("connection failed: {}", conn_result.unwrap_err()));
        let msg = err.to_string();
        assert!(
            msg.contains("connection failed"),
            "unreachable host should produce 'connection failed' error, got: {msg}"
        );
    }

    // ---------------------------------------------------------------
    // TestContext Debug
    // ---------------------------------------------------------------

    #[test]
    fn test_context_has_debug_impl() {
        // Verify that TestContext implements Debug (compile-time check).
        fn assert_debug<T: std::fmt::Debug>() {}
        assert_debug::<TestContext>();
    }

    #[test]
    fn test_context_debug_shows_schema_name() {
        // We can't easily construct a full TestContext without a real DB,
        // but we can test the Debug format by constructing the expected string.
        // The Debug impl should show schema field.
        let schema = "__bsql_test_12345_0";
        let expected = format!("TestContext {{ schema: {:?} }}", schema);
        // Just verify the format pattern is correct
        assert!(expected.contains("TestContext"));
        assert!(expected.contains("schema"));
        assert!(expected.contains(schema));
    }

    // ---------------------------------------------------------------
    // Drop behavior
    // ---------------------------------------------------------------

    #[test]
    fn drop_code_path_with_invalid_url_does_not_panic() {
        // We can't construct a TestContext without a real Pool (async), so we
        // exercise the exact Drop code path manually. This is the same logic
        // that TestContext::drop executes.
        let db_url = "garbage-url";
        let schema_name = "__bsql_test_fake_0";
        // Step 1: Config::from_url — should fail for a garbage URL
        if let Ok(config) = Config::from_url(db_url) {
            // Step 2: Connection::connect — would fail but we shouldn't reach here
            if let Ok(mut conn) = Connection::connect(&config) {
                let _ = conn.simple_query(&format!(
                    "DROP SCHEMA IF EXISTS \"{}\" CASCADE",
                    schema_name
                ));
            }
        }
        // If we get here without panicking, the drop path is safe.
    }

    #[test]
    fn drop_with_garbage_url_does_not_panic() {
        // Directly exercise the Drop code path with an invalid URL.
        // This ensures Config::from_url failure doesn't cause a panic in Drop.
        //
        // We test the conditional logic in Drop:
        //   if let Ok(config) = Config::from_url(&self.db_url) { ... }
        // An invalid URL means Config::from_url returns Err, so drop exits silently.
        let db_url = "not-a-postgres-url";
        let config_result = Config::from_url(db_url);
        assert!(config_result.is_err(), "garbage URL should not parse");
        // The Drop impl would exit at the first `if let Ok(...)` — no panic.
    }

    #[test]
    fn drop_with_valid_url_but_unreachable_host_does_not_panic() {
        // Even if Config::from_url succeeds, Connection::connect can fail.
        // Drop should handle this gracefully.
        let db_url = "postgres://user:pass@127.0.0.1:1/testdb";
        let config = Config::from_url(db_url);
        assert!(config.is_ok(), "URL should parse");
        let conn_result = Connection::connect(&config.unwrap());
        assert!(conn_result.is_err(), "connection to port 1 should fail");
        // The Drop impl would exit at the second `if let Ok(...)` — no panic.
    }

    // ---------------------------------------------------------------
    // Fixture edge cases (tested via the setup function's logic)
    // ---------------------------------------------------------------

    #[test]
    fn empty_fixture_string_is_skipped() {
        // The setup function skips empty fixtures: `if !fixture_sql.trim().is_empty()`
        // Verify the logic directly.
        let fixture = "";
        assert!(fixture.trim().is_empty(), "empty string should be skipped");
    }

    #[test]
    fn whitespace_only_fixture_is_skipped() {
        let fixture = "   \n\t  \n  ";
        assert!(
            fixture.trim().is_empty(),
            "whitespace-only fixture should be skipped"
        );
    }

    #[test]
    fn fixture_with_only_comments_is_not_empty() {
        // SQL comments are not whitespace, so they pass the trim check.
        // PostgreSQL will accept them as valid SQL (no-op).
        let fixture = "-- just a comment\n/* block comment */";
        assert!(
            !fixture.trim().is_empty(),
            "comment-only fixture should NOT be skipped (PG handles it)"
        );
    }

    #[test]
    fn fixture_with_multiple_statements_passes_trim_check() {
        let fixture = "CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);";
        assert!(!fixture.trim().is_empty());
    }

    // ---------------------------------------------------------------
    // Error type verification
    // ---------------------------------------------------------------

    #[test]
    fn missing_env_error_is_connect_variant() {
        let err =
            ConnectError::create("BSQL_DATABASE_URL or DATABASE_URL must be set for #[bsql::test]");
        match err {
            BsqlError::Connect(ref ce) => {
                assert!(ce.message.contains("BSQL_DATABASE_URL"));
            }
            _ => panic!("expected Connect variant"),
        }
    }

    #[test]
    fn invalid_url_error_is_connect_variant() {
        let err = ConnectError::create("invalid database URL: missing postgres:// prefix");
        match err {
            BsqlError::Connect(ref ce) => {
                assert!(ce.message.contains("invalid database URL"));
            }
            _ => panic!("expected Connect variant"),
        }
    }

    #[test]
    fn connection_failed_error_is_connect_variant() {
        let err = ConnectError::create("connection failed: Connection refused");
        match err {
            BsqlError::Connect(ref ce) => {
                assert!(ce.message.contains("connection failed"));
            }
            _ => panic!("expected Connect variant"),
        }
    }

    #[test]
    fn fixture_failed_error_is_connect_variant() {
        let err = ConnectError::create("fixture failed: syntax error at position 5");
        match err {
            BsqlError::Connect(ref ce) => {
                assert!(ce.message.contains("fixture failed"));
            }
            _ => panic!("expected Connect variant"),
        }
    }

    #[test]
    fn schema_creation_failed_error_is_connect_variant() {
        let err = ConnectError::create("failed to create test schema: permission denied");
        match err {
            BsqlError::Connect(ref ce) => {
                assert!(ce.message.contains("failed to create test schema"));
            }
            _ => panic!("expected Connect variant"),
        }
    }

    // ---------------------------------------------------------------
    // Schema name format deep verification
    // ---------------------------------------------------------------

    #[test]
    fn schema_name_has_three_parts() {
        let counter = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let pid = std::process::id();
        let name = format!("__bsql_test_{}_{}", pid, counter);
        // Parts: prefix "__bsql_test", pid, counter
        assert!(name.starts_with("__bsql_test_"));
        let suffix = &name["__bsql_test_".len()..];
        let parts: Vec<&str> = suffix.split('_').collect();
        assert_eq!(parts.len(), 2, "expected PID_COUNTER suffix, got: {suffix}");
        assert_eq!(parts[0], pid.to_string());
        assert_eq!(parts[1], counter.to_string());
    }

    #[test]
    fn schema_name_counter_part_increases() {
        let c1 = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let c2 = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let pid = std::process::id();
        let name1 = format!("__bsql_test_{}_{}", pid, c1);
        let name2 = format!("__bsql_test_{}_{}", pid, c2);
        // Extract counter from name
        let counter1: u64 = name1.rsplit('_').next().unwrap().parse().unwrap();
        let counter2: u64 = name2.rsplit('_').next().unwrap().parse().unwrap();
        assert!(counter2 > counter1);
    }

    // ---------------------------------------------------------------
    // BSQL_DATABASE_URL takes priority over DATABASE_URL
    // ---------------------------------------------------------------

    #[tokio::test]
    async fn bsql_database_url_takes_priority_over_database_url() {
        let orig_bsql = std::env::var("BSQL_DATABASE_URL").ok();
        let orig_db = std::env::var("DATABASE_URL").ok();

        // Set both — BSQL_DATABASE_URL should win
        // Use an invalid URL so we can see which one is used in the error
        std::env::set_var("BSQL_DATABASE_URL", "not-postgres-bsql");
        std::env::set_var("DATABASE_URL", "postgres://user:pass@127.0.0.1:1/realdb");

        let result = setup_test_schema(&[]).await;
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        // Should fail because BSQL_DATABASE_URL is not a valid postgres URL
        assert!(
            msg.contains("invalid database URL"),
            "BSQL_DATABASE_URL should take priority, got: {msg}"
        );

        // Restore
        std::env::remove_var("BSQL_DATABASE_URL");
        std::env::remove_var("DATABASE_URL");
        if let Some(v) = orig_bsql {
            std::env::set_var("BSQL_DATABASE_URL", v);
        }
        if let Some(v) = orig_db {
            std::env::set_var("DATABASE_URL", v);
        }
    }
}