mssql_client/row.rs
1//! Row representation for query results.
2//!
3//! This module implements the `Arc<Bytes>` pattern from ADR-004 for reduced-copy
4//! row data access. The `Row` struct holds a shared reference to the raw packet
5//! buffer, deferring allocation until explicitly requested.
6//!
7//! ## Access Patterns (per ADR-004)
8//!
9//! - `get_bytes()` - Returns borrowed slice into buffer (zero additional allocation)
10//! - `get_str()` - Returns Cow - borrowed if valid UTF-8, owned if conversion needed
11//! - `get_string()` - Allocates new String (explicit allocation)
12//! - `get<T>()` - Type-converting accessor with allocation only if needed
13
14use std::borrow::Cow;
15use std::sync::Arc;
16
17use bytes::Bytes;
18
19use mssql_types::decode::{TypeInfo, decode_value};
20use mssql_types::{FromSql, SqlValue, TypeError};
21
22use crate::blob::BlobReader;
23
24/// Column slice information pointing into the row buffer.
25///
26/// This is the internal representation that enables zero-copy access
27/// to column data within the shared buffer.
28#[derive(Debug, Clone, Copy)]
29#[non_exhaustive]
30pub struct ColumnSlice {
31 /// Offset into the buffer where this column's data begins.
32 pub offset: u32,
33 /// Length of the column data in bytes.
34 pub length: u32,
35 /// Whether this column value is NULL.
36 pub is_null: bool,
37}
38
39impl ColumnSlice {
40 /// Create a new column slice.
41 pub fn new(offset: u32, length: u32, is_null: bool) -> Self {
42 Self {
43 offset,
44 length,
45 is_null,
46 }
47 }
48
49 /// Create a NULL column slice.
50 pub fn null() -> Self {
51 Self {
52 offset: 0,
53 length: 0,
54 is_null: true,
55 }
56 }
57}
58
59/// Column metadata describing a result set column.
60///
61/// This struct is marked `#[non_exhaustive]` to allow adding new fields
62/// in future versions without breaking semver compatibility. Use
63/// [`Column::new()`] or builder methods to construct instances.
64#[derive(Debug, Clone)]
65#[non_exhaustive]
66pub struct Column {
67 /// Column name.
68 pub name: String,
69 /// Column index (0-based).
70 pub index: usize,
71 /// SQL type name (e.g., "INT", "NVARCHAR").
72 pub type_name: String,
73 /// Whether the column allows NULL values.
74 pub nullable: bool,
75 /// Maximum length for variable-length types.
76 pub max_length: Option<u32>,
77 /// Precision for numeric types.
78 pub precision: Option<u8>,
79 /// Scale for numeric types.
80 pub scale: Option<u8>,
81 /// Collation for string types (VARCHAR, CHAR, TEXT).
82 ///
83 /// Used for proper encoding/decoding of non-Unicode string data.
84 /// When present, enables collation-aware decoding that correctly
85 /// handles locale-specific ANSI encodings (e.g., Shift_JIS, GB18030).
86 pub collation: Option<tds_protocol::Collation>,
87}
88
89impl Column {
90 /// Create a new column with basic metadata.
91 pub fn new(name: impl Into<String>, index: usize, type_name: impl Into<String>) -> Self {
92 Self {
93 name: name.into(),
94 index,
95 type_name: type_name.into(),
96 nullable: true,
97 max_length: None,
98 precision: None,
99 scale: None,
100 collation: None,
101 }
102 }
103
104 /// Set whether the column is nullable.
105 #[must_use]
106 pub fn with_nullable(mut self, nullable: bool) -> Self {
107 self.nullable = nullable;
108 self
109 }
110
111 /// Set the maximum length.
112 #[must_use]
113 pub fn with_max_length(mut self, max_length: u32) -> Self {
114 self.max_length = Some(max_length);
115 self
116 }
117
118 /// Set precision and scale for numeric types.
119 #[must_use]
120 pub fn with_precision_scale(mut self, precision: u8, scale: u8) -> Self {
121 self.precision = Some(precision);
122 self.scale = Some(scale);
123 self
124 }
125
126 /// Set the collation for string types.
127 ///
128 /// Used for proper encoding/decoding of non-Unicode string data (VARCHAR, CHAR, TEXT).
129 #[must_use]
130 pub fn with_collation(mut self, collation: tds_protocol::Collation) -> Self {
131 self.collation = Some(collation);
132 self
133 }
134
135 /// Get the encoding name for this column's collation.
136 ///
137 /// Returns the name of the character encoding used for this column's data,
138 /// or "unknown" if the collation is not set or the encoding feature is disabled.
139 ///
140 /// # Examples
141 ///
142 /// - `"Shift_JIS"` - Japanese encoding (LCID 0x0411)
143 /// - `"GB18030"` - Simplified Chinese (LCID 0x0804)
144 /// - `"UTF-8"` - SQL Server 2019+ UTF-8 collation
145 /// - `"windows-1252"` - Latin/Western European (LCID 0x0409)
146 /// - `"unknown"` - No collation or unsupported encoding
147 #[must_use]
148 pub fn encoding_name(&self) -> &'static str {
149 #[cfg(feature = "encoding")]
150 if let Some(ref collation) = self.collation {
151 return collation.encoding_name();
152 }
153 "unknown"
154 }
155
156 /// Check if this column uses UTF-8 encoding.
157 ///
158 /// Returns `true` if the column has a SQL Server 2019+ UTF-8 collation,
159 /// which is indicated by bit 27 (0x0800_0000) being set in the LCID.
160 #[must_use]
161 pub fn is_utf8_collation(&self) -> bool {
162 #[cfg(feature = "encoding")]
163 if let Some(ref collation) = self.collation {
164 return collation.is_utf8();
165 }
166 false
167 }
168
169 /// Convert column metadata to TDS TypeInfo for decoding.
170 ///
171 /// Maps type names to TDS type IDs and constructs appropriate TypeInfo.
172 pub fn to_type_info(&self) -> TypeInfo {
173 let type_id = type_name_to_id(&self.type_name);
174 TypeInfo {
175 type_id,
176 length: self.max_length,
177 scale: self.scale,
178 precision: self.precision,
179 collation: self.collation.map(|c| mssql_types::decode::Collation {
180 lcid: c.lcid,
181 flags: c.sort_id,
182 }),
183 }
184 }
185}
186
187/// Map SQL type name to TDS type ID.
188fn type_name_to_id(name: &str) -> u8 {
189 match name.to_uppercase().as_str() {
190 // Integer types
191 "INT" | "INTEGER" => 0x38,
192 "BIGINT" => 0x7F,
193 "SMALLINT" => 0x34,
194 "TINYINT" => 0x30,
195 "BIT" => 0x32,
196
197 // Floating point
198 "FLOAT" => 0x3E,
199 "REAL" => 0x3B,
200
201 // Decimal/Numeric
202 "DECIMAL" | "NUMERIC" => 0x6C,
203 "MONEY" | "SMALLMONEY" => 0x6E,
204
205 // String types
206 "NVARCHAR" | "NCHAR" | "NTEXT" => 0xE7,
207 "VARCHAR" | "CHAR" | "TEXT" => 0xA7,
208
209 // Binary types
210 "VARBINARY" | "BINARY" | "IMAGE" => 0xA5,
211
212 // Date/Time types
213 "DATE" => 0x28,
214 "TIME" => 0x29,
215 "DATETIME2" => 0x2A,
216 "DATETIMEOFFSET" => 0x2B,
217 "DATETIME" => 0x3D,
218 "SMALLDATETIME" => 0x3F,
219
220 // GUID
221 "UNIQUEIDENTIFIER" => 0x24,
222
223 // XML
224 "XML" => 0xF1,
225
226 // Nullable variants (INTNTYPE, etc.)
227 _ if name.ends_with("N") => 0x26,
228
229 // Default to binary for unknown types
230 _ => 0xA5,
231 }
232}
233
234/// Shared column metadata for a result set.
235///
236/// This is shared across all rows in the result set to avoid
237/// duplicating metadata per row.
238#[derive(Debug, Clone)]
239pub struct ColMetaData {
240 /// Column definitions.
241 pub columns: Arc<[Column]>,
242}
243
244impl ColMetaData {
245 /// Create new column metadata from a list of columns.
246 pub fn new(columns: Vec<Column>) -> Self {
247 Self {
248 columns: columns.into(),
249 }
250 }
251
252 /// Get the number of columns.
253 #[must_use]
254 pub fn len(&self) -> usize {
255 self.columns.len()
256 }
257
258 /// Check if there are no columns.
259 #[must_use]
260 pub fn is_empty(&self) -> bool {
261 self.columns.is_empty()
262 }
263
264 /// Get a column by index.
265 #[must_use]
266 pub fn get(&self, index: usize) -> Option<&Column> {
267 self.columns.get(index)
268 }
269
270 /// Find a column index by name (case-insensitive).
271 #[must_use]
272 pub fn find_by_name(&self, name: &str) -> Option<usize> {
273 self.columns
274 .iter()
275 .position(|c| c.name.eq_ignore_ascii_case(name))
276 }
277}
278
279/// A row from a query result.
280///
281/// Implements the `Arc<Bytes>` pattern from ADR-004 for reduced memory allocation.
282/// The row holds a shared reference to the raw packet buffer and column slice
283/// information, deferring parsing and allocation until values are accessed.
284///
285/// # Memory Model
286///
287/// ```text
288/// Row {
289/// buffer: Arc<Bytes> ──────────► [raw packet data...]
290/// slices: Arc<[ColumnSlice]> ──► [{offset, length, is_null}, ...]
291/// metadata: Arc<ColMetaData> ──► [Column definitions...]
292/// }
293/// ```
294///
295/// Multiple `Row` instances from the same result set share the `metadata`.
296/// The `buffer` and `slices` are unique per row but use `Arc` for cheap cloning.
297///
298/// # Access Patterns
299///
300/// - **Zero-copy:** `get_bytes()`, `get_str()` (when UTF-8 valid)
301/// - **Allocating:** `get_string()`, `get::<String>()`
302/// - **Type-converting:** `get::<T>()` uses `FromSql` trait
303#[derive(Clone)]
304pub struct Row {
305 /// Shared reference to raw packet body containing row data.
306 buffer: Arc<Bytes>,
307 /// Column offsets into buffer.
308 slices: Arc<[ColumnSlice]>,
309 /// Column metadata (shared across result set).
310 metadata: Arc<ColMetaData>,
311 /// Cached parsed values (lazily populated).
312 /// This maintains backward compatibility with code expecting SqlValue access.
313 values: Option<Arc<[SqlValue]>>,
314}
315
316impl Row {
317 /// Create a new row with the `Arc<Bytes>` pattern.
318 ///
319 /// This is the primary constructor for the reduced-copy pattern.
320 pub fn new(buffer: Arc<Bytes>, slices: Arc<[ColumnSlice]>, metadata: Arc<ColMetaData>) -> Self {
321 Self {
322 buffer,
323 slices,
324 metadata,
325 values: None,
326 }
327 }
328
329 /// Create a row from pre-parsed values (backward compatibility).
330 ///
331 /// This constructor supports existing code that works with `SqlValue` directly.
332 /// It's less efficient than the buffer-based approach but maintains compatibility.
333 #[allow(dead_code)]
334 pub(crate) fn from_values(columns: Vec<Column>, values: Vec<SqlValue>) -> Self {
335 let metadata = Arc::new(ColMetaData::new(columns));
336 let slices: Arc<[ColumnSlice]> = values
337 .iter()
338 .enumerate()
339 .map(|(i, v)| ColumnSlice::new(i as u32, 0, v.is_null()))
340 .collect::<Vec<_>>()
341 .into();
342
343 Self {
344 buffer: Arc::new(Bytes::new()),
345 slices,
346 metadata,
347 values: Some(values.into()),
348 }
349 }
350
351 // ========================================================================
352 // Zero-Copy Access Methods (ADR-004)
353 // ========================================================================
354
355 /// Returns borrowed slice into buffer (zero additional allocation).
356 ///
357 /// This is the most efficient access method when you need raw bytes.
358 #[must_use]
359 pub fn get_bytes(&self, index: usize) -> Option<&[u8]> {
360 let slice = self.slices.get(index)?;
361 if slice.is_null {
362 return None;
363 }
364
365 let start = slice.offset as usize;
366 let end = start + slice.length as usize;
367
368 if end <= self.buffer.len() {
369 Some(&self.buffer[start..end])
370 } else {
371 None
372 }
373 }
374
375 /// Returns Cow - borrowed if valid UTF-8, owned if conversion needed.
376 ///
377 /// For UTF-8 data, this returns a borrowed reference (zero allocation).
378 /// For VARCHAR data with collation, uses collation-aware decoding.
379 /// For UTF-16 data (NVARCHAR), decodes as UTF-16LE.
380 ///
381 /// # Collation-Aware Decoding
382 ///
383 /// When the `encoding` feature is enabled and the column has collation metadata,
384 /// VARCHAR data is decoded using the appropriate character encoding based on the
385 /// collation's LCID. This correctly handles:
386 ///
387 /// - Japanese (Shift_JIS/CP932)
388 /// - Simplified Chinese (GB18030/CP936)
389 /// - Traditional Chinese (Big5/CP950)
390 /// - Korean (EUC-KR/CP949)
391 /// - Windows code pages 874, 1250-1258
392 /// - SQL Server 2019+ UTF-8 collations
393 #[must_use]
394 pub fn get_str(&self, index: usize) -> Option<Cow<'_, str>> {
395 let bytes = self.get_bytes(index)?;
396
397 // Try to interpret as UTF-8 first (zero allocation for ASCII/UTF-8 data)
398 match std::str::from_utf8(bytes) {
399 Ok(s) => Some(Cow::Borrowed(s)),
400 Err(_) => {
401 // Check if we have collation metadata for this column
402 #[cfg(feature = "encoding")]
403 if let Some(column) = self.metadata.get(index) {
404 if let Some(ref collation) = column.collation {
405 // Use collation-aware decoding for VARCHAR/CHAR types
406 if let Some(encoding) = collation.encoding() {
407 let (decoded, _, had_errors) = encoding.decode(bytes);
408 if had_errors {
409 tracing::warn!(
410 column_name = %column.name,
411 column_index = index,
412 encoding = %encoding.name(),
413 lcid = collation.lcid,
414 byte_len = bytes.len(),
415 "collation-aware decoding had errors, falling back to UTF-16LE"
416 );
417 } else {
418 return Some(Cow::Owned(decoded.into_owned()));
419 }
420 } else {
421 tracing::debug!(
422 column_name = %column.name,
423 column_index = index,
424 lcid = collation.lcid,
425 "no encoding found for LCID, falling back to UTF-16LE"
426 );
427 }
428 }
429 }
430
431 // Assume UTF-16LE (SQL Server NVARCHAR encoding)
432 // This requires allocation for the conversion
433 let utf16: Vec<u16> = bytes
434 .chunks_exact(2)
435 .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
436 .collect();
437
438 String::from_utf16(&utf16).ok().map(Cow::Owned)
439 }
440 }
441 }
442
443 /// Allocates new String (explicit allocation).
444 ///
445 /// Use this when you need an owned String.
446 #[must_use]
447 pub fn get_string(&self, index: usize) -> Option<String> {
448 self.get_str(index).map(|cow| cow.into_owned())
449 }
450
451 // ========================================================================
452 // Streaming Access (LOB support)
453 // ========================================================================
454
455 /// Get a streaming reader for a binary/text column.
456 ///
457 /// Returns a [`BlobReader`] that implements [`tokio::io::AsyncRead`] for
458 /// streaming access to large binary or text columns. This is useful for:
459 ///
460 /// - Streaming large data to files without fully loading into memory
461 /// - Processing data in chunks with progress tracking
462 /// - Copying data between I/O destinations efficiently
463 ///
464 /// # Supported Column Types
465 ///
466 /// - `VARBINARY`, `VARBINARY(MAX)`
467 /// - `VARCHAR`, `VARCHAR(MAX)`
468 /// - `NVARCHAR`, `NVARCHAR(MAX)`
469 /// - `TEXT`, `NTEXT`, `IMAGE` (legacy types)
470 /// - `XML`
471 ///
472 /// # Example
473 ///
474 /// ```rust,ignore
475 /// use tokio::io::AsyncWriteExt;
476 ///
477 /// // Stream a large VARBINARY(MAX) column to a file
478 /// let mut reader = row.get_stream(0)?;
479 /// let mut file = tokio::fs::File::create("output.bin").await?;
480 /// tokio::io::copy(&mut reader, &mut file).await?;
481 /// ```
482 ///
483 /// # Returns
484 ///
485 /// - `Some(BlobReader)` if the column contains binary/text data
486 /// - `None` if the column is NULL or the index is out of bounds
487 #[must_use]
488 pub fn get_stream(&self, index: usize) -> Option<BlobReader> {
489 let slice = self.slices.get(index)?;
490 if slice.is_null {
491 return None;
492 }
493
494 let start = slice.offset as usize;
495 let end = start + slice.length as usize;
496
497 if end <= self.buffer.len() {
498 // Use zero-copy slicing from Arc<Bytes>
499 let data = self.buffer.slice(start..end);
500 Some(BlobReader::from_bytes(data))
501 } else {
502 None
503 }
504 }
505
506 /// Get a streaming reader for a binary/text column by name.
507 ///
508 /// See [`get_stream`](Self::get_stream) for details.
509 ///
510 /// # Example
511 ///
512 /// ```rust,ignore
513 /// let mut reader = row.get_stream_by_name("document_content")?;
514 /// // Process the blob stream...
515 /// ```
516 #[must_use]
517 pub fn get_stream_by_name(&self, name: &str) -> Option<BlobReader> {
518 let index = self.metadata.find_by_name(name)?;
519 self.get_stream(index)
520 }
521
522 // ========================================================================
523 // Type-Converting Access (FromSql trait)
524 // ========================================================================
525
526 /// Get a value by column index with type conversion.
527 ///
528 /// Uses the `FromSql` trait to convert the raw value to the requested type.
529 pub fn get<T: FromSql>(&self, index: usize) -> Result<T, TypeError> {
530 // If we have cached values, use them
531 if let Some(ref values) = self.values {
532 return values
533 .get(index)
534 .ok_or_else(|| TypeError::TypeMismatch {
535 expected: "valid column index",
536 actual: format!("index {index} out of bounds"),
537 })
538 .and_then(T::from_sql);
539 }
540
541 // Otherwise, parse on demand from the buffer
542 let slice = self
543 .slices
544 .get(index)
545 .ok_or_else(|| TypeError::TypeMismatch {
546 expected: "valid column index",
547 actual: format!("index {index} out of bounds"),
548 })?;
549
550 if slice.is_null {
551 return Err(TypeError::UnexpectedNull);
552 }
553
554 // Parse via SqlValue then convert to target type
555 // Note: parse_value uses zero-copy buffer slicing (Arc<Bytes>::slice)
556 let value = self.parse_value(index, slice)?;
557 T::from_sql(&value)
558 }
559
560 /// Get a value by column name with type conversion.
561 pub fn get_by_name<T: FromSql>(&self, name: &str) -> Result<T, TypeError> {
562 let index = self
563 .metadata
564 .find_by_name(name)
565 .ok_or_else(|| TypeError::TypeMismatch {
566 expected: "valid column name",
567 actual: format!("column '{name}' not found"),
568 })?;
569
570 self.get(index)
571 }
572
573 /// Try to get a value by column index, returning None if NULL or not found.
574 pub fn try_get<T: FromSql>(&self, index: usize) -> Option<T> {
575 // If we have cached values, use them
576 if let Some(ref values) = self.values {
577 return values
578 .get(index)
579 .and_then(|v| T::from_sql_nullable(v).ok().flatten());
580 }
581
582 // Otherwise check the slice
583 let slice = self.slices.get(index)?;
584 if slice.is_null {
585 return None;
586 }
587
588 self.get(index).ok()
589 }
590
591 /// Try to get a value by column name, returning None if NULL or not found.
592 pub fn try_get_by_name<T: FromSql>(&self, name: &str) -> Option<T> {
593 let index = self.metadata.find_by_name(name)?;
594 self.try_get(index)
595 }
596
597 // ========================================================================
598 // Raw Value Access (backward compatibility)
599 // ========================================================================
600
601 /// Get the raw SQL value by index.
602 ///
603 /// Note: This may allocate if values haven't been cached.
604 #[must_use]
605 pub fn get_raw(&self, index: usize) -> Option<SqlValue> {
606 if let Some(ref values) = self.values {
607 return values.get(index).cloned();
608 }
609
610 let slice = self.slices.get(index)?;
611 self.parse_value(index, slice).ok()
612 }
613
614 /// Get the raw SQL value by column name.
615 #[must_use]
616 pub fn get_raw_by_name(&self, name: &str) -> Option<SqlValue> {
617 let index = self.metadata.find_by_name(name)?;
618 self.get_raw(index)
619 }
620
621 // ========================================================================
622 // Metadata Access
623 // ========================================================================
624
625 /// Get the number of columns in the row.
626 #[must_use]
627 pub fn len(&self) -> usize {
628 self.slices.len()
629 }
630
631 /// Check if the row is empty.
632 #[must_use]
633 pub fn is_empty(&self) -> bool {
634 self.slices.is_empty()
635 }
636
637 /// Get the column metadata.
638 #[must_use]
639 pub fn columns(&self) -> &[Column] {
640 &self.metadata.columns
641 }
642
643 /// Get the shared column metadata.
644 #[must_use]
645 pub fn metadata(&self) -> &Arc<ColMetaData> {
646 &self.metadata
647 }
648
649 /// Check if a column value is NULL.
650 #[must_use]
651 pub fn is_null(&self, index: usize) -> bool {
652 self.slices.get(index).map(|s| s.is_null).unwrap_or(true)
653 }
654
655 /// Check if a column value is NULL by name.
656 #[must_use]
657 pub fn is_null_by_name(&self, name: &str) -> bool {
658 self.metadata
659 .find_by_name(name)
660 .map(|i| self.is_null(i))
661 .unwrap_or(true)
662 }
663
664 // ========================================================================
665 // Internal Helpers
666 // ========================================================================
667
668 /// Parse a value from the buffer at the given slice.
669 ///
670 /// Uses the mssql-types decode module for efficient binary parsing.
671 /// Optimized to use zero-copy buffer slicing via Arc<Bytes>.
672 fn parse_value(&self, index: usize, slice: &ColumnSlice) -> Result<SqlValue, TypeError> {
673 if slice.is_null {
674 return Ok(SqlValue::Null);
675 }
676
677 let column = self
678 .metadata
679 .get(index)
680 .ok_or_else(|| TypeError::TypeMismatch {
681 expected: "valid column metadata",
682 actual: format!("no metadata for column {index}"),
683 })?;
684
685 // Calculate byte range for this column
686 let start = slice.offset as usize;
687 let end = start + slice.length as usize;
688
689 // Validate range
690 if end > self.buffer.len() {
691 return Err(TypeError::TypeMismatch {
692 expected: "valid byte range",
693 actual: format!(
694 "range {}..{} exceeds buffer length {}",
695 start,
696 end,
697 self.buffer.len()
698 ),
699 });
700 }
701
702 // Convert column metadata to TypeInfo for the decode module
703 let type_info = column.to_type_info();
704
705 // Use zero-copy slice of the buffer instead of allocating
706 // This avoids the overhead of Bytes::copy_from_slice
707 let mut buf = self.buffer.slice(start..end);
708
709 // Use the unified decode module for efficient parsing
710 decode_value(&mut buf, &type_info)
711 }
712}
713
714impl std::fmt::Debug for Row {
715 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
716 f.debug_struct("Row")
717 .field("columns", &self.metadata.columns.len())
718 .field("buffer_size", &self.buffer.len())
719 .field("has_cached_values", &self.values.is_some())
720 .finish()
721 }
722}
723
724/// Iterator over row values as SqlValue.
725pub struct RowIter<'a> {
726 row: &'a Row,
727 index: usize,
728}
729
730impl Iterator for RowIter<'_> {
731 type Item = SqlValue;
732
733 fn next(&mut self) -> Option<Self::Item> {
734 if self.index >= self.row.len() {
735 return None;
736 }
737 let value = self.row.get_raw(self.index);
738 self.index += 1;
739 value
740 }
741
742 fn size_hint(&self) -> (usize, Option<usize>) {
743 let remaining = self.row.len() - self.index;
744 (remaining, Some(remaining))
745 }
746}
747
748impl<'a> IntoIterator for &'a Row {
749 type Item = SqlValue;
750 type IntoIter = RowIter<'a>;
751
752 fn into_iter(self) -> Self::IntoIter {
753 RowIter {
754 row: self,
755 index: 0,
756 }
757 }
758}
759
760#[cfg(test)]
761#[allow(clippy::unwrap_used)]
762mod tests {
763 use super::*;
764
765 #[test]
766 fn test_column_slice_null() {
767 let slice = ColumnSlice::null();
768 assert!(slice.is_null);
769 assert_eq!(slice.offset, 0);
770 assert_eq!(slice.length, 0);
771 }
772
773 #[test]
774 fn test_column_metadata() {
775 let col = Column::new("id", 0, "INT")
776 .with_nullable(false)
777 .with_precision_scale(10, 0);
778
779 assert_eq!(col.name, "id");
780 assert_eq!(col.index, 0);
781 assert!(!col.nullable);
782 assert_eq!(col.precision, Some(10));
783 }
784
785 #[test]
786 fn test_col_metadata_find_by_name() {
787 let meta = ColMetaData::new(vec![
788 Column::new("id", 0, "INT"),
789 Column::new("Name", 1, "NVARCHAR"),
790 ]);
791
792 assert_eq!(meta.find_by_name("id"), Some(0));
793 assert_eq!(meta.find_by_name("ID"), Some(0)); // case-insensitive
794 assert_eq!(meta.find_by_name("name"), Some(1));
795 assert_eq!(meta.find_by_name("unknown"), None);
796 }
797
798 #[test]
799 fn test_row_from_values_backward_compat() {
800 let columns = vec![
801 Column::new("id", 0, "INT"),
802 Column::new("name", 1, "NVARCHAR"),
803 ];
804 let values = vec![SqlValue::Int(42), SqlValue::String("Alice".to_string())];
805
806 let row = Row::from_values(columns, values);
807
808 assert_eq!(row.len(), 2);
809 assert_eq!(row.get::<i32>(0).unwrap(), 42);
810 assert_eq!(row.get_by_name::<String>("name").unwrap(), "Alice");
811 }
812
813 #[test]
814 fn test_row_is_null() {
815 let columns = vec![
816 Column::new("id", 0, "INT"),
817 Column::new("nullable_col", 1, "NVARCHAR"),
818 ];
819 let values = vec![SqlValue::Int(1), SqlValue::Null];
820
821 let row = Row::from_values(columns, values);
822
823 assert!(!row.is_null(0));
824 assert!(row.is_null(1));
825 assert!(row.is_null(99)); // Out of bounds returns true
826 }
827
828 #[test]
829 fn test_row_get_bytes_with_buffer() {
830 let buffer = Arc::new(Bytes::from_static(b"Hello World"));
831 let slices: Arc<[ColumnSlice]> = vec![
832 ColumnSlice::new(0, 5, false), // "Hello"
833 ColumnSlice::new(6, 5, false), // "World"
834 ]
835 .into();
836 let meta = Arc::new(ColMetaData::new(vec![
837 Column::new("greeting", 0, "VARCHAR"),
838 Column::new("subject", 1, "VARCHAR"),
839 ]));
840
841 let row = Row::new(buffer, slices, meta);
842
843 assert_eq!(row.get_bytes(0), Some(b"Hello".as_slice()));
844 assert_eq!(row.get_bytes(1), Some(b"World".as_slice()));
845 }
846
847 #[test]
848 fn test_row_get_str() {
849 let buffer = Arc::new(Bytes::from_static(b"Test"));
850 let slices: Arc<[ColumnSlice]> = vec![ColumnSlice::new(0, 4, false)].into();
851 let meta = Arc::new(ColMetaData::new(vec![Column::new("val", 0, "VARCHAR")]));
852
853 let row = Row::new(buffer, slices, meta);
854
855 let s = row.get_str(0).unwrap();
856 assert_eq!(s, "Test");
857 // Should be borrowed for valid UTF-8
858 assert!(matches!(s, Cow::Borrowed(_)));
859 }
860
861 #[test]
862 fn test_row_metadata_access() {
863 let columns = vec![Column::new("col1", 0, "INT")];
864 let row = Row::from_values(columns, vec![SqlValue::Int(1)]);
865
866 assert_eq!(row.columns().len(), 1);
867 assert_eq!(row.columns()[0].name, "col1");
868 assert_eq!(row.metadata().len(), 1);
869 }
870
871 #[test]
872 fn test_row_get_stream() {
873 let buffer = Arc::new(Bytes::from_static(b"Hello, World!"));
874 let slices: Arc<[ColumnSlice]> = vec![
875 ColumnSlice::new(0, 5, false), // "Hello"
876 ColumnSlice::new(7, 5, false), // "World"
877 ColumnSlice::null(), // NULL column
878 ]
879 .into();
880 let meta = Arc::new(ColMetaData::new(vec![
881 Column::new("greeting", 0, "VARBINARY"),
882 Column::new("subject", 1, "VARBINARY"),
883 Column::new("nullable", 2, "VARBINARY"),
884 ]));
885
886 let row = Row::new(buffer, slices, meta);
887
888 // Get stream for first column
889 let reader = row.get_stream(0).unwrap();
890 assert_eq!(reader.len(), Some(5));
891 assert_eq!(reader.as_bytes().as_ref(), b"Hello");
892
893 // Get stream for second column
894 let reader = row.get_stream(1).unwrap();
895 assert_eq!(reader.len(), Some(5));
896 assert_eq!(reader.as_bytes().as_ref(), b"World");
897
898 // NULL column returns None
899 assert!(row.get_stream(2).is_none());
900
901 // Out of bounds returns None
902 assert!(row.get_stream(99).is_none());
903 }
904
905 #[test]
906 fn test_row_get_stream_by_name() {
907 let buffer = Arc::new(Bytes::from_static(b"Binary data here"));
908 let slices: Arc<[ColumnSlice]> = vec![ColumnSlice::new(0, 11, false)].into();
909 let meta = Arc::new(ColMetaData::new(vec![Column::new(
910 "document",
911 0,
912 "VARBINARY",
913 )]));
914
915 let row = Row::new(buffer, slices, meta);
916
917 // Get by name (case-insensitive)
918 let reader = row.get_stream_by_name("document").unwrap();
919 assert_eq!(reader.len(), Some(11));
920
921 let reader = row.get_stream_by_name("DOCUMENT").unwrap();
922 assert_eq!(reader.len(), Some(11));
923
924 // Unknown column returns None
925 assert!(row.get_stream_by_name("unknown").is_none());
926 }
927}