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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Zero-copy row deserialization traits and utilities.
//!
//! This module provides traits for efficient row deserialization that minimizes
//! memory allocations by borrowing data directly from the database row.
//!
//! # Zero-Copy Deserialization
//!
//! The `FromRowRef` trait enables zero-copy deserialization for types that can
//! borrow string data directly from the row:
//!
//! ```rust,ignore
//! use prax_query::row::{FromRowRef, RowRef};
//!
//! struct UserRef<'a> {
//!     id: i32,
//!     email: &'a str,  // Borrowed from row
//!     name: Option<&'a str>,
//! }
//!
//! impl<'a> FromRowRef<'a> for UserRef<'a> {
//!     fn from_row_ref(row: &'a impl RowRef) -> Result<Self, RowError> {
//!         Ok(Self {
//!             id: row.get("id")?,
//!             email: row.get_str("email")?,
//!             name: row.get_str_opt("name")?,
//!         })
//!     }
//! }
//! ```
//!
//! # Performance
//!
//! Zero-copy deserialization can significantly reduce allocations:
//! - String fields borrow directly from row buffer (no allocation)
//! - Integer/float fields are copied (no difference)
//! - Optional fields return `Option<&'a str>` instead of `Option<String>`

use std::borrow::Cow;
use std::fmt;

/// Error type for row deserialization.
#[derive(Debug, Clone)]
pub enum RowError {
    /// Column not found.
    ColumnNotFound(String),
    /// Type conversion error.
    TypeConversion { column: String, message: String },
    /// Null value in non-nullable column.
    UnexpectedNull(String),
}

impl fmt::Display for RowError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ColumnNotFound(col) => write!(f, "column '{}' not found", col),
            Self::TypeConversion { column, message } => {
                write!(f, "type conversion error for '{}': {}", column, message)
            }
            Self::UnexpectedNull(col) => write!(f, "unexpected null in column '{}'", col),
        }
    }
}

impl std::error::Error for RowError {}

/// A database row that supports zero-copy access.
///
/// This trait is implemented by database-specific row types to enable
/// efficient data extraction without unnecessary copying.
pub trait RowRef {
    /// Get an integer column value.
    fn get_i32(&self, column: &str) -> Result<i32, RowError>;

    /// Get an optional integer column value.
    fn get_i32_opt(&self, column: &str) -> Result<Option<i32>, RowError>;

    /// Get a 64-bit integer column value.
    fn get_i64(&self, column: &str) -> Result<i64, RowError>;

    /// Get an optional 64-bit integer column value.
    fn get_i64_opt(&self, column: &str) -> Result<Option<i64>, RowError>;

    /// Get a float column value.
    fn get_f64(&self, column: &str) -> Result<f64, RowError>;

    /// Get an optional float column value.
    fn get_f64_opt(&self, column: &str) -> Result<Option<f64>, RowError>;

    /// Get a boolean column value.
    fn get_bool(&self, column: &str) -> Result<bool, RowError>;

    /// Get an optional boolean column value.
    fn get_bool_opt(&self, column: &str) -> Result<Option<bool>, RowError>;

    /// Get a string column value as a borrowed reference (zero-copy).
    ///
    /// This is the key method for zero-copy deserialization. The returned
    /// string slice borrows directly from the row's internal buffer.
    fn get_str(&self, column: &str) -> Result<&str, RowError>;

    /// Get an optional string column value as a borrowed reference.
    fn get_str_opt(&self, column: &str) -> Result<Option<&str>, RowError>;

    /// Get a string column value as owned (for cases where ownership is needed).
    fn get_string(&self, column: &str) -> Result<String, RowError> {
        self.get_str(column).map(|s| s.to_string())
    }

    /// Get an optional string as owned.
    fn get_string_opt(&self, column: &str) -> Result<Option<String>, RowError> {
        self.get_str_opt(column)
            .map(|opt| opt.map(|s| s.to_string()))
    }

    /// Get a bytes column value as a borrowed reference (zero-copy).
    fn get_bytes(&self, column: &str) -> Result<&[u8], RowError>;

    /// Get optional bytes as borrowed reference.
    fn get_bytes_opt(&self, column: &str) -> Result<Option<&[u8]>, RowError>;

    /// Get column value as a Cow, borrowing when possible.
    fn get_cow_str(&self, column: &str) -> Result<Cow<'_, str>, RowError> {
        self.get_str(column).map(Cow::Borrowed)
    }

    fn get_datetime_utc(&self, column: &str) -> Result<chrono::DateTime<chrono::Utc>, RowError> {
        Err(unsupported_get(column, "datetime_utc"))
    }
    fn get_datetime_utc_opt(
        &self,
        column: &str,
    ) -> Result<Option<chrono::DateTime<chrono::Utc>>, RowError> {
        Err(unsupported_get(column, "datetime_utc_opt"))
    }
    fn get_naive_datetime(&self, column: &str) -> Result<chrono::NaiveDateTime, RowError> {
        Err(unsupported_get(column, "naive_datetime"))
    }
    fn get_naive_datetime_opt(
        &self,
        column: &str,
    ) -> Result<Option<chrono::NaiveDateTime>, RowError> {
        Err(unsupported_get(column, "naive_datetime_opt"))
    }
    fn get_naive_date(&self, column: &str) -> Result<chrono::NaiveDate, RowError> {
        Err(unsupported_get(column, "naive_date"))
    }
    fn get_naive_date_opt(&self, column: &str) -> Result<Option<chrono::NaiveDate>, RowError> {
        Err(unsupported_get(column, "naive_date_opt"))
    }
    fn get_naive_time(&self, column: &str) -> Result<chrono::NaiveTime, RowError> {
        Err(unsupported_get(column, "naive_time"))
    }
    fn get_naive_time_opt(&self, column: &str) -> Result<Option<chrono::NaiveTime>, RowError> {
        Err(unsupported_get(column, "naive_time_opt"))
    }
    fn get_uuid(&self, column: &str) -> Result<uuid::Uuid, RowError> {
        Err(unsupported_get(column, "uuid"))
    }
    fn get_uuid_opt(&self, column: &str) -> Result<Option<uuid::Uuid>, RowError> {
        Err(unsupported_get(column, "uuid_opt"))
    }
    fn get_json(&self, column: &str) -> Result<serde_json::Value, RowError> {
        Err(unsupported_get(column, "json"))
    }
    fn get_json_opt(&self, column: &str) -> Result<Option<serde_json::Value>, RowError> {
        Err(unsupported_get(column, "json_opt"))
    }
    fn get_decimal(&self, column: &str) -> Result<rust_decimal::Decimal, RowError> {
        Err(unsupported_get(column, "decimal"))
    }
    fn get_decimal_opt(&self, column: &str) -> Result<Option<rust_decimal::Decimal>, RowError> {
        Err(unsupported_get(column, "decimal_opt"))
    }

    /// Get a pgvector column as a dense `Vec<f32>`.
    ///
    /// Default impl errors with `unsupported_get`; `prax-postgres`
    /// overrides this on its `RowRef` impl to decode the on-wire
    /// pgvector representation. Used by the blanket
    /// `FromColumn for Vec<f32>` impl below so schema-generated
    /// structs with a `Vector(N)` field compile out of the box.
    fn get_vector(&self, column: &str) -> Result<Vec<f32>, RowError> {
        Err(unsupported_get(column, "vector"))
    }

    /// Check whether the named column is NULL in this row.
    ///
    /// The default implementation delegates to `get_str_opt` — every
    /// driver backend already implements that one. Drivers with a
    /// faster null probe (e.g. postgres's `row.try_get::<_, Option<&str>>`
    /// avoids a full string allocation) can override this method.
    ///
    /// Used by the blanket `impl<T: FromColumn> FromColumn for Option<T>`
    /// to dispatch between a nullable decode and the inner type's
    /// non-null decode, so user-defined enums and other custom types
    /// can round-trip through a nullable column without needing a
    /// bespoke `FromColumn for Option<MyEnum>` (which the orphan rule
    /// would forbid the consumer crate from writing).
    fn is_null(&self, column: &str) -> Result<bool, RowError> {
        self.get_str_opt(column).map(|opt| opt.is_none())
    }
}

/// Build a default `TypeConversion` error for a `RowRef::get_*` method that a
/// driver has not overridden. Keeps the error phrasing identical across every
/// extended getter so a debug log like `"uuid not supported by this row type"`
/// always looks the same no matter which getter a model hit.
fn unsupported_get(column: &str, getter: &str) -> RowError {
    RowError::TypeConversion {
        column: column.to_string(),
        message: format!("{getter} not supported by this row type"),
    }
}

/// Map a driver-level error into a `RowError::TypeConversion` tagged with the
/// column the caller asked for. Shared by every driver's `RowRef` bridge so
/// the diagnostic message shape is identical across Postgres, SQLite, MySQL,
/// and MSSQL. The happy path is an unchanged `Ok(value)`.
pub fn into_row_error<T, E: std::fmt::Display>(
    column: &str,
    res: Result<T, E>,
) -> Result<T, RowError> {
    res.map_err(|e| RowError::TypeConversion {
        column: column.to_string(),
        message: e.to_string(),
    })
}

/// Trait for types that can be deserialized from a row reference (zero-copy).
///
/// This trait uses lifetimes to enable borrowing string data directly
/// from the row, avoiding allocations.
pub trait FromRowRef<'a>: Sized {
    /// Deserialize from a row reference.
    fn from_row_ref(row: &'a impl RowRef) -> Result<Self, RowError>;
}

/// Trait for types that can be deserialized from a row (owning).
///
/// This is the traditional deserialization trait that takes ownership
/// of all data.
pub trait FromRow: Sized {
    /// Deserialize from a row.
    fn from_row(row: &impl RowRef) -> Result<Self, RowError>;
}

// Blanket implementation: any FromRow can be used with any row
impl<T: FromRow> FromRowRef<'_> for T {
    fn from_row_ref(row: &impl RowRef) -> Result<Self, RowError> {
        T::from_row(row)
    }
}

/// A row iterator that yields zero-copy deserialized values.
pub struct RowRefIter<'a, R: RowRef, T: FromRowRef<'a>> {
    rows: std::slice::Iter<'a, R>,
    _marker: std::marker::PhantomData<T>,
}

impl<'a, R: RowRef, T: FromRowRef<'a>> RowRefIter<'a, R, T> {
    /// Create a new row iterator.
    pub fn new(rows: &'a [R]) -> Self {
        Self {
            rows: rows.iter(),
            _marker: std::marker::PhantomData,
        }
    }
}

impl<'a, R: RowRef, T: FromRowRef<'a>> Iterator for RowRefIter<'a, R, T> {
    type Item = Result<T, RowError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.rows.next().map(|row| T::from_row_ref(row))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.rows.size_hint()
    }
}

impl<'a, R: RowRef, T: FromRowRef<'a>> ExactSizeIterator for RowRefIter<'a, R, T> {}

/// A collected result that can either borrow or own data.
///
/// This is useful for caching query results while still supporting
/// zero-copy deserialization for fresh queries.
#[derive(Debug, Clone)]
pub enum RowData<'a> {
    /// Borrowed string data.
    Borrowed(&'a str),
    /// Owned string data.
    Owned(String),
}

impl<'a> RowData<'a> {
    /// Get the string value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Borrowed(s) => s,
            Self::Owned(s) => s,
        }
    }

    /// Convert to owned data.
    pub fn into_owned(self) -> String {
        match self {
            Self::Borrowed(s) => s.to_string(),
            Self::Owned(s) => s,
        }
    }

    /// Create borrowed data.
    pub const fn borrowed(s: &'a str) -> Self {
        Self::Borrowed(s)
    }

    /// Create owned data.
    pub fn owned(s: impl Into<String>) -> Self {
        Self::Owned(s.into())
    }
}

impl<'a> From<&'a str> for RowData<'a> {
    fn from(s: &'a str) -> Self {
        Self::Borrowed(s)
    }
}

impl From<String> for RowData<'static> {
    fn from(s: String) -> Self {
        Self::Owned(s)
    }
}

impl<'a> AsRef<str> for RowData<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

/// Macro to implement FromRow for simple structs.
///
/// This generates efficient deserialization code that minimizes allocations.
///
/// # Example
///
/// ```rust,ignore
/// use prax_query::impl_from_row;
///
/// struct User {
///     id: i32,
///     email: String,
///     name: Option<String>,
/// }
///
/// impl_from_row!(User {
///     id: i32,
///     email: String,
///     name: Option<String>,
/// });
/// ```
#[macro_export]
macro_rules! impl_from_row {
    ($type:ident { $($field:ident : i32),* $(,)? }) => {
        impl $crate::row::FromRow for $type {
            fn from_row(row: &impl $crate::row::RowRef) -> Result<Self, $crate::row::RowError> {
                Ok(Self {
                    $(
                        $field: row.get_i32(stringify!($field))?,
                    )*
                })
            }
        }
    };
    ($type:ident { $($field:ident : $field_type:ty),* $(,)? }) => {
        impl $crate::row::FromRow for $type {
            fn from_row(row: &impl $crate::row::RowRef) -> Result<Self, $crate::row::RowError> {
                Ok(Self {
                    $(
                        $field: $crate::row::_get_typed_value::<$field_type>(row, stringify!($field))?,
                    )*
                })
            }
        }
    };
}

/// Helper function for the impl_from_row macro.
#[doc(hidden)]
pub fn _get_typed_value<T: FromColumn>(row: &impl RowRef, column: &str) -> Result<T, RowError> {
    T::from_column(row, column)
}

/// Trait for types that can be extracted from a column.
pub trait FromColumn: Sized {
    /// Extract value from a row column.
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError>;
}

impl FromColumn for i32 {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_i32(column)
    }
}

impl FromColumn for i64 {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_i64(column)
    }
}

impl FromColumn for f64 {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_f64(column)
    }
}

impl FromColumn for bool {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_bool(column)
    }
}

impl FromColumn for String {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_string(column)
    }
}

impl FromColumn for Vec<u8> {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_bytes(column).map(|b| b.to_vec())
    }
}

impl FromColumn for chrono::DateTime<chrono::Utc> {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_datetime_utc(column)
    }
}
impl FromColumn for chrono::NaiveDateTime {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_naive_datetime(column)
    }
}
impl FromColumn for chrono::NaiveDate {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_naive_date(column)
    }
}
impl FromColumn for chrono::NaiveTime {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_naive_time(column)
    }
}
impl FromColumn for uuid::Uuid {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_uuid(column)
    }
}
impl FromColumn for serde_json::Value {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_json(column)
    }
}
impl FromColumn for rust_decimal::Decimal {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_decimal(column)
    }
}

/// Dense pgvector columns decode into `Vec<f32>`. The schema-generated
/// client uses this for `Vector(N)` and `HalfVector(N)` scalar fields.
/// The underlying driver implements `RowRef::get_vector` — drivers that
/// don't have a pgvector binding will surface an unsupported error
/// at query time rather than at compile time.
impl FromColumn for Vec<f32> {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        row.get_vector(column)
    }
}

/// Blanket impl so every `FromColumn` type also satisfies
/// `FromColumn` through `Option<T>` without each consumer needing a
/// hand-written nullable wrapper — schema-generated enum types can't
/// write their own `impl FromColumn for Option<MyEnum>` because of the
/// orphan rule (both `Option` and `FromColumn` are foreign from the
/// consumer crate's perspective).
///
/// Uses `RowRef::is_null` to short-circuit null rows to `None`; the
/// non-null path delegates to `T::from_column`. Drivers that had a
/// faster native `Option<primitive>` path previously now go through
/// this blanket — the extra `is_null` round-trip is a small
/// per-column cost in exchange for the orphan-rule unblock.
impl<T: FromColumn> FromColumn for Option<T> {
    fn from_column(row: &impl RowRef, column: &str) -> Result<Self, RowError> {
        if row.is_null(column)? {
            Ok(None)
        } else {
            T::from_column(row, column).map(Some)
        }
    }
}

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

    // Mock row for testing
    struct MockRow {
        data: std::collections::HashMap<String, String>,
    }

    impl RowRef for MockRow {
        fn get_i32(&self, column: &str) -> Result<i32, RowError> {
            self.data
                .get(column)
                .ok_or_else(|| RowError::ColumnNotFound(column.to_string()))?
                .parse()
                .map_err(|e| RowError::TypeConversion {
                    column: column.to_string(),
                    message: format!("{}", e),
                })
        }

        fn get_i32_opt(&self, column: &str) -> Result<Option<i32>, RowError> {
            match self.data.get(column) {
                Some(v) if v == "NULL" => Ok(None),
                Some(v) => v.parse().map(Some).map_err(|e| RowError::TypeConversion {
                    column: column.to_string(),
                    message: format!("{}", e),
                }),
                None => Ok(None),
            }
        }

        fn get_i64(&self, column: &str) -> Result<i64, RowError> {
            self.data
                .get(column)
                .ok_or_else(|| RowError::ColumnNotFound(column.to_string()))?
                .parse()
                .map_err(|e| RowError::TypeConversion {
                    column: column.to_string(),
                    message: format!("{}", e),
                })
        }

        fn get_i64_opt(&self, column: &str) -> Result<Option<i64>, RowError> {
            match self.data.get(column) {
                Some(v) if v == "NULL" => Ok(None),
                Some(v) => v.parse().map(Some).map_err(|e| RowError::TypeConversion {
                    column: column.to_string(),
                    message: format!("{}", e),
                }),
                None => Ok(None),
            }
        }

        fn get_f64(&self, column: &str) -> Result<f64, RowError> {
            self.data
                .get(column)
                .ok_or_else(|| RowError::ColumnNotFound(column.to_string()))?
                .parse()
                .map_err(|e| RowError::TypeConversion {
                    column: column.to_string(),
                    message: format!("{}", e),
                })
        }

        fn get_f64_opt(&self, column: &str) -> Result<Option<f64>, RowError> {
            match self.data.get(column) {
                Some(v) if v == "NULL" => Ok(None),
                Some(v) => v.parse().map(Some).map_err(|e| RowError::TypeConversion {
                    column: column.to_string(),
                    message: format!("{}", e),
                }),
                None => Ok(None),
            }
        }

        fn get_bool(&self, column: &str) -> Result<bool, RowError> {
            let v = self
                .data
                .get(column)
                .ok_or_else(|| RowError::ColumnNotFound(column.to_string()))?;
            match v.as_str() {
                "true" | "t" | "1" => Ok(true),
                "false" | "f" | "0" => Ok(false),
                _ => Err(RowError::TypeConversion {
                    column: column.to_string(),
                    message: "invalid boolean".to_string(),
                }),
            }
        }

        fn get_bool_opt(&self, column: &str) -> Result<Option<bool>, RowError> {
            match self.data.get(column) {
                Some(v) if v == "NULL" => Ok(None),
                Some(v) => match v.as_str() {
                    "true" | "t" | "1" => Ok(Some(true)),
                    "false" | "f" | "0" => Ok(Some(false)),
                    _ => Err(RowError::TypeConversion {
                        column: column.to_string(),
                        message: "invalid boolean".to_string(),
                    }),
                },
                None => Ok(None),
            }
        }

        fn get_str(&self, column: &str) -> Result<&str, RowError> {
            self.data
                .get(column)
                .map(|s| s.as_str())
                .ok_or_else(|| RowError::ColumnNotFound(column.to_string()))
        }

        fn get_str_opt(&self, column: &str) -> Result<Option<&str>, RowError> {
            match self.data.get(column) {
                Some(v) if v == "NULL" => Ok(None),
                Some(v) => Ok(Some(v.as_str())),
                None => Ok(None),
            }
        }

        fn get_bytes(&self, column: &str) -> Result<&[u8], RowError> {
            self.data
                .get(column)
                .map(|s| s.as_bytes())
                .ok_or_else(|| RowError::ColumnNotFound(column.to_string()))
        }

        fn get_bytes_opt(&self, column: &str) -> Result<Option<&[u8]>, RowError> {
            match self.data.get(column) {
                Some(v) if v == "NULL" => Ok(None),
                Some(v) => Ok(Some(v.as_bytes())),
                None => Ok(None),
            }
        }
    }

    #[test]
    fn test_row_ref_get_i32() {
        let mut data = std::collections::HashMap::new();
        data.insert("id".to_string(), "42".to_string());
        let row = MockRow { data };

        assert_eq!(row.get_i32("id").unwrap(), 42);
    }

    #[test]
    fn test_row_ref_get_str_zero_copy() {
        let mut data = std::collections::HashMap::new();
        data.insert("email".to_string(), "test@example.com".to_string());
        let row = MockRow { data };

        let email = row.get_str("email").unwrap();
        assert_eq!(email, "test@example.com");
        // Note: In a real implementation, this would be zero-copy
        // borrowing directly from the row's buffer
    }

    #[test]
    fn test_row_data() {
        let borrowed: RowData = RowData::borrowed("hello");
        assert_eq!(borrowed.as_str(), "hello");

        let owned: RowData = RowData::owned("world".to_string());
        assert_eq!(owned.as_str(), "world");
    }

    #[test]
    fn default_datetime_method_errors() {
        let mut data = std::collections::HashMap::new();
        data.insert("created_at".into(), "2026-04-27T00:00:00Z".into());
        let row = MockRow { data };
        assert!(matches!(
            row.get_datetime_utc("created_at"),
            Err(RowError::TypeConversion { .. })
        ));
    }
}