bsql-core 0.24.0

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
618
619
620
621
622
623
//! Query dispatch via [`QueryTarget`] — the runtime contract between generated
//! code and the pool/connection/transaction.
//!
//! Code generated by `bsql::query!` converts the user-supplied executor into a
//! [`QueryTarget`] via `Into`, then calls `query_raw` / `query_raw_readonly` /
//! `execute_raw` on it. This enum dispatch replaces the old `Executor` trait
//! and eliminates `Mutex` from `PoolConnection` and `Transaction`.

use bsql_driver_postgres::arena::release_arena;
use bsql_driver_postgres::codec::Encode;
use bsql_driver_postgres::{Arena, QueryResult};

use crate::error::{BsqlError, BsqlResult};
use crate::pool::{Pool, PoolConnection};
use crate::transaction::Transaction;

/// Owned query result that carries its arena alongside the result metadata.
///
/// Generated code calls `.row(i)` to access individual rows. This struct
/// bundles the arena with the result so callsites don't manage arenas manually.
pub struct OwnedResult {
    pub result: QueryResult,
    arena: Arena,
}

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

impl OwnedResult {
    /// Create without arena — for queries that use data_buf instead of arena.
    /// Zero allocation: Arena::empty() allocates nothing.
    pub(crate) fn without_arena(result: QueryResult) -> Self {
        Self {
            result,
            arena: Arena::empty(),
        }
    }

    /// Number of rows.
    #[inline]
    pub fn len(&self) -> usize {
        self.result.len()
    }

    /// Whether the result set is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.result.is_empty()
    }

    /// Get a row by index.
    #[inline]
    pub fn row(&self, idx: usize) -> bsql_driver_postgres::Row<'_> {
        self.result.row(idx, &self.arena)
    }

    /// Iterate over rows.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = bsql_driver_postgres::Row<'_>> {
        self.result.rows(&self.arena)
    }
}

impl Drop for OwnedResult {
    fn drop(&mut self) {
        // Return arena to thread-local pool.
        let arena = std::mem::take(&mut self.arena);
        release_arena(arena);
        // Return data buffer to thread-local pool for reuse by next query.
        if let Some(buf) = self.result.take_data_buf() {
            bsql_driver_postgres::release_resp_buf(buf);
        }
        // Return column offsets buffer to thread-local pool.
        let col_offsets = self.result.take_col_offsets();
        if col_offsets.capacity() > 0 {
            bsql_driver_postgres::release_col_offsets(col_offsets);
        }
    }
}

// ---------------------------------------------------------------------------
// QueryTarget — enum dispatch for Pool / PoolConnection / Transaction
// ---------------------------------------------------------------------------

/// Concrete enum for query dispatch. Replaces the `Executor` trait.
///
/// Generated code converts the user-supplied executor (`&Pool`,
/// `&mut PoolConnection`, or `&mut Transaction`) into `QueryTarget` via
/// `Into`, then calls `query_raw` / `query_raw_readonly` / `execute_raw`.
///
/// `Pool` takes a shared reference (`&Pool`) because it acquires from the
/// pool internally. `PoolConnection` and `Transaction` take exclusive
/// references (`&mut`) — no `Mutex` needed.
pub enum QueryTarget<'a> {
    Pool(&'a Pool),
    Conn(&'a mut PoolConnection),
    Tx(&'a mut Transaction),
}

impl<'a> From<&'a Pool> for QueryTarget<'a> {
    #[inline]
    fn from(pool: &'a Pool) -> Self {
        QueryTarget::Pool(pool)
    }
}

impl<'a> From<&'a mut PoolConnection> for QueryTarget<'a> {
    #[inline]
    fn from(conn: &'a mut PoolConnection) -> Self {
        QueryTarget::Conn(conn)
    }
}

impl<'a> From<&'a mut Transaction> for QueryTarget<'a> {
    #[inline]
    fn from(tx: &'a mut Transaction) -> Self {
        QueryTarget::Tx(tx)
    }
}

// --- Async QueryTarget methods ---

#[cfg(feature = "async")]
impl<'a> QueryTarget<'a> {
    /// Execute a query and return all rows.
    #[inline]
    pub async fn query_raw(
        self,
        sql: &str,
        sql_hash: u64,
        params: &[&(dyn Encode + Sync)],
    ) -> BsqlResult<OwnedResult> {
        match self {
            QueryTarget::Pool(pool) => {
                let mut guard = pool.inner.acquire_async().await.map_err(BsqlError::from)?;
                let result = guard
                    .query_async(sql, sql_hash, params)
                    .await
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            QueryTarget::Conn(conn) => {
                let result = conn
                    .inner
                    .query(sql, sql_hash, params)
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            QueryTarget::Tx(tx) => tx.query_inner(sql, sql_hash, params),
        }
    }

    /// Execute a read-only query. Routes to replicas for Pool when configured.
    #[inline]
    pub async fn query_raw_readonly(
        self,
        sql: &str,
        sql_hash: u64,
        params: &[&(dyn Encode + Sync)],
    ) -> BsqlResult<OwnedResult> {
        match self {
            QueryTarget::Pool(pool) => {
                let driver_pool = pool.read_pool.as_ref().unwrap_or(&pool.inner);
                let mut guard = driver_pool.acquire_async().await.map_err(BsqlError::from)?;
                let result = guard
                    .query_async(sql, sql_hash, params)
                    .await
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            // PoolConnection and Transaction don't have replicas; same as query_raw.
            QueryTarget::Conn(conn) => {
                let result = conn
                    .inner
                    .query(sql, sql_hash, params)
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            QueryTarget::Tx(tx) => tx.query_inner(sql, sql_hash, params),
        }
    }

    /// Execute a query and return the number of affected rows.
    #[inline]
    pub async fn execute_raw(
        self,
        sql: &str,
        sql_hash: u64,
        params: &[&(dyn Encode + Sync)],
    ) -> BsqlResult<u64> {
        match self {
            QueryTarget::Pool(pool) => {
                let mut guard = pool.inner.acquire_async().await.map_err(BsqlError::from)?;
                guard
                    .execute_async(sql, sql_hash, params)
                    .await
                    .map_err(BsqlError::from_driver_query)
            }
            QueryTarget::Conn(conn) => conn
                .inner
                .execute(sql, sql_hash, params)
                .map_err(BsqlError::from_driver_query),
            QueryTarget::Tx(tx) => tx.execute_inner(sql, sql_hash, params),
        }
    }
}

// --- Sync QueryTarget methods ---

#[cfg(not(feature = "async"))]
impl<'a> QueryTarget<'a> {
    /// Execute a query and return all rows.
    #[inline]
    pub fn query_raw(
        self,
        sql: &str,
        sql_hash: u64,
        params: &[&(dyn Encode + Sync)],
    ) -> BsqlResult<OwnedResult> {
        match self {
            QueryTarget::Pool(pool) => {
                let mut guard = pool.inner.acquire().map_err(BsqlError::from)?;
                let result = guard
                    .query(sql, sql_hash, params)
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            QueryTarget::Conn(conn) => {
                let result = conn
                    .inner
                    .query(sql, sql_hash, params)
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            QueryTarget::Tx(tx) => tx.query_inner(sql, sql_hash, params),
        }
    }

    /// Execute a read-only query. Routes to replicas for Pool when configured.
    #[inline]
    pub fn query_raw_readonly(
        self,
        sql: &str,
        sql_hash: u64,
        params: &[&(dyn Encode + Sync)],
    ) -> BsqlResult<OwnedResult> {
        match self {
            QueryTarget::Pool(pool) => {
                let driver_pool = pool.read_pool.as_ref().unwrap_or(&pool.inner);
                let mut guard = driver_pool.acquire().map_err(BsqlError::from)?;
                let result = guard
                    .query(sql, sql_hash, params)
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            QueryTarget::Conn(conn) => {
                let result = conn
                    .inner
                    .query(sql, sql_hash, params)
                    .map_err(BsqlError::from_driver_query)?;
                Ok(OwnedResult::without_arena(result))
            }
            QueryTarget::Tx(tx) => tx.query_inner(sql, sql_hash, params),
        }
    }

    /// Execute a query and return the number of affected rows.
    #[inline]
    pub fn execute_raw(
        self,
        sql: &str,
        sql_hash: u64,
        params: &[&(dyn Encode + Sync)],
    ) -> BsqlResult<u64> {
        match self {
            QueryTarget::Pool(pool) => {
                let mut guard = pool.inner.acquire().map_err(BsqlError::from)?;
                guard
                    .execute(sql, sql_hash, params)
                    .map_err(BsqlError::from_driver_query)
            }
            QueryTarget::Conn(conn) => conn
                .inner
                .execute(sql, sql_hash, params)
                .map_err(BsqlError::from_driver_query),
            QueryTarget::Tx(tx) => tx.execute_inner(sql, sql_hash, params),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bsql_driver_postgres::arena::{acquire_arena, release_arena};
    use bsql_driver_postgres::{ColumnDesc, QueryResult};
    use std::sync::Arc;

    /// Helper: build an OwnedResult with `n` rows and `num_cols` columns.
    /// Each column offset entry is a dummy (0, 0) pair — sufficient for
    /// testing len/is_empty/row-count without decoding real data.
    fn make_owned_result(num_rows: usize, num_cols: usize) -> OwnedResult {
        let arena = acquire_arena();
        let cols: Arc<[ColumnDesc]> = (0..num_cols)
            .map(|i| ColumnDesc {
                name: format!("c{i}").into(),
                type_oid: 23, // int4
                type_size: 4,
                table_oid: 0,
                column_id: 0,
            })
            .collect::<Vec<_>>()
            .into();

        let col_offsets: Vec<(usize, i32)> = vec![(0, -1); num_rows * num_cols]; // NULL columns
        let result = QueryResult::from_parts(col_offsets, num_cols, cols, 0);
        OwnedResult { result, arena }
    }

    // --- OwnedResult ---

    #[test]
    fn owned_result_new_zero_rows() {
        let owned = make_owned_result(0, 2);
        assert_eq!(owned.len(), 0);
        assert!(owned.is_empty());
    }

    #[test]
    fn owned_result_new_single_row() {
        let owned = make_owned_result(1, 3);
        assert_eq!(owned.len(), 1);
        assert!(!owned.is_empty());
    }

    #[test]
    fn owned_result_new_multiple_rows() {
        let owned = make_owned_result(5, 2);
        assert_eq!(owned.len(), 5);
        assert!(!owned.is_empty());
    }

    // --- OwnedResult::row ---

    #[test]
    fn owned_result_row_access() {
        let owned = make_owned_result(3, 2);
        // Should not panic for valid indices
        let _r0 = owned.row(0);
        let _r1 = owned.row(1);
        let _r2 = owned.row(2);
    }

    #[test]
    #[should_panic]
    fn owned_result_row_out_of_bounds_panics() {
        let owned = make_owned_result(2, 1);
        let _r = owned.row(2); // out of bounds
    }

    // --- OwnedResult::iter ---

    #[test]
    fn owned_result_iter_count() {
        let owned = make_owned_result(4, 2);
        let count = owned.iter().count();
        assert_eq!(count, 4);
    }

    #[test]
    fn owned_result_iter_empty() {
        let owned = make_owned_result(0, 2);
        let count = owned.iter().count();
        assert_eq!(count, 0);
    }

    // --- OwnedResult::Drop releases arena back to pool ---

    #[test]
    fn owned_result_drop_releases_arena() {
        // Acquire an arena, wrap it in OwnedResult, drop it.
        // After drop, acquiring should succeed (arena was returned to pool).
        let owned = make_owned_result(1, 1);
        drop(owned);
        // If the arena was released, we can acquire again without issue.
        let arena = acquire_arena();
        release_arena(arena);
    }

    // --- OwnedResult with zero columns ---

    #[test]
    fn owned_result_zero_columns() {
        // Commands like INSERT without RETURNING have 0 columns
        let arena = acquire_arena();
        let cols: Arc<[ColumnDesc]> = Arc::from(Vec::new());
        let result = QueryResult::from_parts(vec![], 0, cols, 42);
        let owned = OwnedResult { result, arena };
        assert_eq!(owned.len(), 0);
        assert!(owned.is_empty());
        assert_eq!(owned.result.affected_rows(), 42);
    }

    // --- OwnedResult::without_arena ---

    #[test]
    fn owned_result_without_arena_len_zero() {
        let cols: Arc<[ColumnDesc]> = Arc::from(Vec::new());
        let result = QueryResult::from_parts(vec![], 0, cols, 0);
        let owned = OwnedResult::without_arena(result);
        assert_eq!(owned.len(), 0);
    }

    #[test]
    fn owned_result_without_arena_is_empty() {
        let cols: Arc<[ColumnDesc]> = Arc::from(Vec::new());
        let result = QueryResult::from_parts(vec![], 0, cols, 0);
        let owned = OwnedResult::without_arena(result);
        assert!(owned.is_empty());
    }

    #[test]
    fn owned_result_without_arena_with_rows() {
        let cols: Arc<[ColumnDesc]> = vec![ColumnDesc {
            name: "c0".into(),
            type_oid: 23,
            type_size: 4,
            table_oid: 0,
            column_id: 0,
        }]
        .into();
        let col_offsets = vec![(0, -1); 3]; // 3 rows, 1 col each (all NULL)
        let result = QueryResult::from_parts(col_offsets, 1, cols, 0);
        let owned = OwnedResult::without_arena(result);
        assert_eq!(owned.len(), 3);
        assert!(!owned.is_empty());
    }

    // --- OwnedResult Debug ---

    #[test]
    fn owned_result_debug_format() {
        let owned = make_owned_result(5, 2);
        let dbg = format!("{owned:?}");
        assert!(
            dbg.contains("OwnedResult"),
            "Debug should contain struct name: {dbg}"
        );
        assert!(dbg.contains("5"), "Debug should contain row count: {dbg}");
    }

    // --- OwnedResult drop without_arena variant ---

    #[test]
    fn owned_result_without_arena_drop_does_not_panic() {
        let cols: Arc<[ColumnDesc]> = Arc::from(Vec::new());
        let result = QueryResult::from_parts(vec![], 0, cols, 0);
        let owned = OwnedResult::without_arena(result);
        drop(owned); // Must not panic — arena is Arena::empty()
    }

    // --- Pool / PoolConnection / Transaction Send constraints ---
    // PoolConnection and Transaction are Send but NOT Sync (no Mutex).

    #[test]
    fn pool_is_send_and_sync() {
        fn _assert_send<T: Send>() {}
        fn _assert_sync<T: Sync>() {}
        _assert_send::<crate::pool::Pool>();
        _assert_sync::<crate::pool::Pool>();
    }

    #[test]
    fn pool_connection_is_send() {
        fn _assert_send<T: Send>() {}
        _assert_send::<crate::pool::PoolConnection>();
    }

    #[test]
    fn transaction_is_send() {
        fn _assert_send<T: Send>() {}
        _assert_send::<crate::transaction::Transaction>();
    }

    #[test]
    fn owned_result_is_send_and_sync() {
        fn _assert_send<T: Send>() {}
        fn _assert_sync<T: Sync>() {}
        _assert_send::<OwnedResult>();
        _assert_sync::<OwnedResult>();
    }

    // --- QueryTarget From impls ---

    #[test]
    fn query_target_from_pool_compiles() {
        // Compile-time test: From<&Pool> for QueryTarget exists
        fn _check<'a>(_: &'a Pool) -> QueryTarget<'a> {
            unimplemented!()
        }
    }

    #[test]
    fn query_target_from_pool_connection_compiles() {
        fn _check<'a>(_: &'a mut PoolConnection) -> QueryTarget<'a> {
            unimplemented!()
        }
    }

    #[test]
    fn query_target_from_transaction_compiles() {
        fn _check<'a>(_: &'a mut Transaction) -> QueryTarget<'a> {
            unimplemented!()
        }
    }

    // --- OwnedResult affected_rows on without_arena variant ---

    #[test]
    fn owned_result_without_arena_affected_rows() {
        let cols: Arc<[ColumnDesc]> = Arc::from(Vec::new());
        let result = QueryResult::from_parts(vec![], 0, cols, 42);
        let owned = OwnedResult::without_arena(result);
        assert_eq!(owned.result.affected_rows(), 42);
    }

    #[test]
    fn owned_result_without_arena_affected_rows_zero() {
        let cols: Arc<[ColumnDesc]> = Arc::from(Vec::new());
        let result = QueryResult::from_parts(vec![], 0, cols, 0);
        let owned = OwnedResult::without_arena(result);
        assert_eq!(owned.result.affected_rows(), 0);
    }

    // --- OwnedResult iter yields correct rows ---

    #[test]
    fn owned_result_iter_yields_all_rows() {
        let owned = make_owned_result(3, 1);
        let rows: Vec<_> = owned.iter().collect();
        assert_eq!(rows.len(), 3);
    }

    // --- OwnedResult Debug format with 0 rows ---

    #[test]
    fn owned_result_debug_format_zero_rows() {
        let owned = make_owned_result(0, 2);
        let dbg = format!("{owned:?}");
        assert!(dbg.contains("OwnedResult"), "should contain name: {dbg}");
        assert!(dbg.contains("0"), "should contain 0: {dbg}");
    }

    // --- OwnedResult row panics for empty result ---

    #[test]
    #[should_panic]
    fn owned_result_row_panics_on_empty() {
        let owned = make_owned_result(0, 1);
        let _r = owned.row(0);
    }

    // --- QueryTarget variant discrimination ---

    #[test]
    fn query_target_pool_variant_matches() {
        fn _check_pool<'a>(pool: &'a Pool) {
            let qt: QueryTarget<'a> = pool.into();
            assert!(matches!(qt, QueryTarget::Pool(_)));
        }
    }

    #[test]
    fn query_target_conn_variant_matches() {
        fn _check_conn<'a>(conn: &'a mut PoolConnection) {
            let qt: QueryTarget<'a> = conn.into();
            assert!(matches!(qt, QueryTarget::Conn(_)));
        }
    }

    #[test]
    fn query_target_tx_variant_matches() {
        fn _check_tx<'a>(tx: &'a mut Transaction) {
            let qt: QueryTarget<'a> = tx.into();
            assert!(matches!(qt, QueryTarget::Tx(_)));
        }
    }

    // --- OwnedResult large row count ---

    #[test]
    fn owned_result_large_row_count() {
        let owned = make_owned_result(1000, 2);
        assert_eq!(owned.len(), 1000);
        assert!(!owned.is_empty());
        assert_eq!(owned.iter().count(), 1000);
    }

    // --- OwnedResult single column ---

    #[test]
    fn owned_result_single_column_row_access() {
        let owned = make_owned_result(2, 1);
        let _r0 = owned.row(0);
        let _r1 = owned.row(1);
        assert_eq!(owned.len(), 2);
    }

    // --- Multiple drops don't panic ---

    #[test]
    fn owned_result_drop_twice_via_option() {
        let owned = make_owned_result(1, 1);
        let mut opt = Some(owned);
        opt.take(); // first drop
                    // second drop on None — should not panic
        drop(opt);
    }
}