duckdb 1.10502.0

Ergonomic wrapper for DuckDB
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
use std::{convert, sync::Arc};

use super::{Error, Result, Statement};
use crate::types::{self, EnumType, FromSql, FromSqlError, ListType, ValueRef};

use arrow::{
    array::{
        self, Array, ArrayRef, DictionaryArray, FixedSizeBinaryArray, FixedSizeListArray, ListArray, MapArray,
        StructArray,
    },
    datatypes::*,
};
use fallible_iterator::FallibleIterator;
use fallible_streaming_iterator::FallibleStreamingIterator;
use rust_decimal::prelude::*;

/// An handle for the resulting rows of a query.
#[must_use = "Rows is lazy and will do nothing unless consumed"]
pub struct Rows<'stmt> {
    pub(crate) stmt: Option<&'stmt Statement<'stmt>>,
    arr: Arc<Option<StructArray>>,
    row: Option<Row<'stmt>>,
    current_row: usize,
    current_batch_row: usize,
}

impl<'stmt> Rows<'stmt> {
    #[inline]
    fn reset(&mut self) {
        self.current_row = 0;
        self.current_batch_row = 0;
        self.arr = Arc::new(None);
    }

    /// Attempt to get the next row from the query. Returns `Ok(Some(Row))` if
    /// there is another row, `Err(...)` if there was an error
    /// getting the next row, and `Ok(None)` if all rows have been retrieved.
    ///
    /// ## Note
    ///
    /// This interface is not compatible with Rust's `Iterator` trait, because
    /// the lifetime of the returned row is tied to the lifetime of `self`.
    /// This is a fallible "streaming iterator". For a more natural interface,
    /// consider using [`query_map`](crate::Statement::query_map) or
    /// [`query_and_then`](crate::Statement::query_and_then) instead, which
    /// return types that implement `Iterator`.
    #[allow(clippy::should_implement_trait)] // cannot implement Iterator
    #[inline]
    pub fn next(&mut self) -> Result<Option<&Row<'stmt>>> {
        self.advance()?;
        Ok((*self).get())
    }

    #[inline]
    fn batch_row_count(&self) -> usize {
        if self.arr.is_none() {
            return 0;
        }
        self.arr.as_ref().as_ref().unwrap().len()
    }

    /// Map over this `Rows`, converting it to a [`Map`], which
    /// implements `FallibleIterator`.
    ///
    /// **Note:** This method requires the closure to return `duckdb::Result<B>`.
    /// If you need to use custom error types, consider using [`and_then`](Self::and_then)
    /// instead, which allows any error type that implements `From<duckdb::Error>`.
    ///
    /// ```rust,no_run
    /// use fallible_iterator::FallibleIterator;
    /// # use duckdb::{Result, Statement};
    /// fn query(stmt: &mut Statement) -> Result<Vec<i64>> {
    ///     let rows = stmt.query([])?;
    ///     rows.map(|r| r.get(0)).collect()
    /// }
    /// ```
    // FIXME Hide FallibleStreamingIterator::map
    #[inline]
    pub fn map<F, B>(self, f: F) -> Map<'stmt, F>
    where
        F: FnMut(&Row<'_>) -> Result<B>,
    {
        Map { rows: self, f }
    }

    /// Map over this `Rows`, converting it to a [`MappedRows`], which
    /// implements `Iterator`.
    #[inline]
    pub fn mapped<F, B>(self, f: F) -> MappedRows<'stmt, F>
    where
        F: FnMut(&Row<'_>) -> Result<B>,
    {
        MappedRows { rows: self, map: f }
    }

    /// Map over this `Rows` with a fallible function, converting it to a
    /// [`AndThenRows`], which implements `Iterator` (instead of
    /// `FallibleStreamingIterator`).
    #[inline]
    pub fn and_then<F, T, E>(self, f: F) -> AndThenRows<'stmt, F>
    where
        F: FnMut(&Row<'_>) -> Result<T, E>,
    {
        AndThenRows { rows: self, map: f }
    }

    /// Access the underlying statement
    ///
    /// This method provides a way to access the `Statement` that created these `Rows`
    /// without additional borrowing conflicts. This is particularly useful when you need
    /// to access statement metadata (like column count or names) while iterating over results.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use duckdb::{Connection, Result};
    /// fn process_results(conn: &Connection) -> Result<()> {
    ///     let mut stmt = conn.prepare("SELECT id, name FROM people")?;
    ///     let mut rows = stmt.query([])?;
    ///
    ///     let column_count = rows.as_ref().unwrap().column_count();
    ///     println!("Processing {} columns", column_count);
    ///
    ///     while let Some(row) = rows.next()? {
    ///         // Process row...
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn as_ref(&self) -> Option<&Statement<'stmt>> {
        self.stmt
    }
}

impl<'stmt> Rows<'stmt> {
    #[inline]
    pub(crate) fn new(stmt: &'stmt Statement<'stmt>) -> Self {
        Rows {
            stmt: Some(stmt),
            arr: Arc::new(None),
            row: None,
            current_row: 0,
            current_batch_row: 0,
        }
    }

    #[inline]
    pub(crate) fn get_expected_row(&mut self) -> Result<&Row<'stmt>> {
        match self.next()? {
            Some(row) => Ok(row),
            None => Err(Error::QueryReturnedNoRows),
        }
    }
}

/// `F` is used to transform the _streaming_ iterator into a _fallible_
/// iterator.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Map<'stmt, F> {
    rows: Rows<'stmt>,
    f: F,
}

impl<F, B> FallibleIterator for Map<'_, F>
where
    F: FnMut(&Row<'_>) -> Result<B>,
{
    type Error = Error;
    type Item = B;

    #[inline]
    fn next(&mut self) -> Result<Option<B>> {
        match self.rows.next()? {
            Some(v) => Ok(Some((self.f)(v)?)),
            None => Ok(None),
        }
    }
}

/// An iterator over the mapped resulting rows of a query.
///
/// `F` is used to transform the _streaming_ iterator into a _standard_
/// iterator.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct MappedRows<'stmt, F> {
    rows: Rows<'stmt>,
    map: F,
}

impl<T, F> Iterator for MappedRows<'_, F>
where
    F: FnMut(&Row<'_>) -> Result<T>,
{
    type Item = Result<T>;

    #[inline]
    fn next(&mut self) -> Option<Result<T>> {
        let map = &mut self.map;
        self.rows.next().transpose().map(|row_result| row_result.and_then(map))
    }
}

/// An iterator over the mapped resulting rows of a query, with an Error type
/// unifying with Error.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct AndThenRows<'stmt, F> {
    rows: Rows<'stmt>,
    map: F,
}

impl<T, E, F> Iterator for AndThenRows<'_, F>
where
    E: convert::From<Error>,
    F: FnMut(&Row<'_>) -> Result<T, E>,
{
    type Item = Result<T, E>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let map = &mut self.map;
        self.rows
            .next()
            .transpose()
            .map(|row_result| row_result.map_err(E::from).and_then(map))
    }
}

/// `FallibleStreamingIterator` differs from the standard library's `Iterator`
/// in two ways:
/// * each call to `next` (sqlite3_step) can fail.
/// * returned `Row` is valid until `next` is called again or `Statement` is
///   reset or finalized.
///
/// While these iterators cannot be used with Rust `for` loops, `while let`
/// loops offer a similar level of ergonomics:
/// ```rust,no_run
/// # use duckdb::{Result, Statement};
/// fn query(stmt: &mut Statement) -> Result<()> {
///     let mut rows = stmt.query([])?;
///     while let Some(row) = rows.next()? {
///         // scan columns value
///     }
///     Ok(())
/// }
/// ```
impl<'stmt> FallibleStreamingIterator for Rows<'stmt> {
    type Error = Error;
    type Item = Row<'stmt>;

    #[inline]
    fn advance(&mut self) -> Result<()> {
        match self.stmt {
            Some(stmt) => {
                if self.current_row < stmt.row_count() {
                    if self.current_batch_row >= self.batch_row_count() {
                        self.arr = Arc::new(stmt.step());
                        if self.arr.is_none() {
                            self.row = None;
                            return Ok(());
                        }
                        self.current_batch_row = 0;
                    }
                    self.row = Some(Row {
                        stmt,
                        arr: self.arr.clone(),
                        current_row: self.current_batch_row,
                    });
                    self.current_row += 1;
                    self.current_batch_row += 1;
                    Ok(())
                } else {
                    self.reset();
                    self.row = None;
                    Ok(())
                }
            }
            None => {
                self.row = None;
                Ok(())
            }
        }
    }

    #[inline]
    fn get(&self) -> Option<&Row<'stmt>> {
        self.row.as_ref()
    }
}

/// A single result row of a query.
pub struct Row<'stmt> {
    pub(crate) stmt: &'stmt Statement<'stmt>,
    arr: Arc<Option<StructArray>>,
    current_row: usize,
}

#[allow(clippy::needless_lifetimes)]
impl<'stmt> Row<'stmt> {
    /// Get the value of a particular column of the result row.
    ///
    /// ## Failure
    ///
    /// Panics if calling [`row.get(idx)`](Row::get) would return an error,
    /// including:
    ///
    /// * If the underlying DuckDB column type is not a valid type as a source
    ///   for `T`
    /// * If the underlying DuckDB integral value is outside the range
    ///   representable by `T`
    /// * If `idx` is outside the range of columns in the returned query
    pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T {
        self.get(idx).unwrap()
    }

    /// Get the value of a particular column of the result row.
    ///
    /// ## Failure
    ///
    /// Returns an `Error::InvalidColumnType` if the underlying DuckDB column
    /// type is not a valid type as a source for `T`.
    ///
    /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid
    /// column range for this row.
    ///
    /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column
    /// name for this row.
    ///
    /// If the result type is i128 (which requires the `i128_blob` feature to be
    /// enabled), and the underlying DuckDB column is a blob whose size is not
    /// 16 bytes, `Error::InvalidColumnType` will also be returned.
    pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
        let idx = idx.idx(self.stmt)?;
        let value = self.value_ref(self.current_row, idx);
        FromSql::column_result(value).map_err(|err| match err {
            FromSqlError::InvalidType => {
                Error::InvalidColumnType(idx, self.stmt.column_name_unwrap(idx).into(), value.data_type())
            }
            FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i),
            FromSqlError::Other(err) => Error::FromSqlConversionFailure(idx, value.data_type(), err),
            #[cfg(feature = "uuid")]
            FromSqlError::InvalidUuidSize(_) => {
                Error::InvalidColumnType(idx, self.stmt.column_name_unwrap(idx).into(), value.data_type())
            }
        })
    }

    /// Get the value of a particular column of the result row as a `ValueRef`,
    /// allowing data to be read out of a row without copying.
    ///
    /// This `ValueRef` is valid only as long as this Row, which is enforced by
    /// it's lifetime. This means that while this method is completely safe,
    /// it can be somewhat difficult to use, and most callers will be better
    /// served by [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap).
    ///
    /// ## Failure
    ///
    /// Returns an `Error::InvalidColumnIndex` if `idx` is outside the valid
    /// column range for this row.
    ///
    /// Returns an `Error::InvalidColumnName` if `idx` is not a valid column
    /// name for this row.
    pub fn get_ref<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> {
        let idx = idx.idx(self.stmt)?;
        // Narrowing from `ValueRef<'stmt>` (which `self.stmt.value_ref(idx)`
        // returns) to `ValueRef<'a>` is needed because it's only valid until
        // the next call to sqlite3_step.
        let val_ref = self.value_ref(self.current_row, idx);
        Ok(val_ref)
    }

    fn value_ref(&self, row: usize, col: usize) -> ValueRef<'_> {
        let column = self.arr.as_ref().as_ref().unwrap().column(col);
        Self::value_ref_internal(row, col, column)
    }

    pub(crate) fn value_ref_internal(row: usize, col: usize, column: &ArrayRef) -> ValueRef<'_> {
        if column.is_null(row) {
            return ValueRef::Null;
        }
        // duckdb.cpp SetArrowFormat
        // https://github.com/duckdb/duckdb/blob/71f1c7a7e4b8737cff5e78d1f090c54f5e78e17b/src/main/query_result.cpp#L148
        match column.data_type() {
            DataType::Utf8 => {
                let array = column.as_any().downcast_ref::<array::StringArray>().unwrap();
                ValueRef::from(array.value(row))
            }
            DataType::LargeUtf8 => {
                let array = column.as_any().downcast_ref::<array::LargeStringArray>().unwrap();
                ValueRef::from(array.value(row))
            }
            DataType::Binary => {
                let array = column.as_any().downcast_ref::<array::BinaryArray>().unwrap();
                ValueRef::Blob(array.value(row))
            }
            DataType::LargeBinary => {
                let array = column.as_any().downcast_ref::<array::LargeBinaryArray>().unwrap();
                ValueRef::Blob(array.value(row))
            }
            DataType::FixedSizeBinary(_) => {
                let array = column.as_any().downcast_ref::<FixedSizeBinaryArray>().unwrap();
                ValueRef::Blob(array.value(row))
            }
            DataType::Boolean => {
                let array = column.as_any().downcast_ref::<array::BooleanArray>().unwrap();
                ValueRef::Boolean(array.value(row))
            }
            DataType::Int8 => {
                let array = column.as_any().downcast_ref::<array::Int8Array>().unwrap();
                ValueRef::TinyInt(array.value(row))
            }
            DataType::Int16 => {
                let array = column.as_any().downcast_ref::<array::Int16Array>().unwrap();
                ValueRef::SmallInt(array.value(row))
            }
            DataType::Int32 => {
                let array = column.as_any().downcast_ref::<array::Int32Array>().unwrap();
                ValueRef::Int(array.value(row))
            }
            DataType::Int64 => {
                let array = column.as_any().downcast_ref::<array::Int64Array>().unwrap();
                ValueRef::BigInt(array.value(row))
            }
            DataType::UInt8 => {
                let array = column.as_any().downcast_ref::<array::UInt8Array>().unwrap();
                ValueRef::UTinyInt(array.value(row))
            }
            DataType::UInt16 => {
                let array = column.as_any().downcast_ref::<array::UInt16Array>().unwrap();
                ValueRef::USmallInt(array.value(row))
            }
            DataType::UInt32 => {
                let array = column.as_any().downcast_ref::<array::UInt32Array>().unwrap();
                ValueRef::UInt(array.value(row))
            }
            DataType::UInt64 => {
                let array = column.as_any().downcast_ref::<array::UInt64Array>().unwrap();
                ValueRef::UBigInt(array.value(row))
            }
            DataType::Float16 => {
                let array = column.as_any().downcast_ref::<array::Float32Array>().unwrap();
                ValueRef::Float(array.value(row))
            }
            DataType::Float32 => {
                let array = column.as_any().downcast_ref::<array::Float32Array>().unwrap();
                ValueRef::Float(array.value(row))
            }
            DataType::Float64 => {
                let array = column.as_any().downcast_ref::<array::Float64Array>().unwrap();
                ValueRef::Double(array.value(row))
            }
            DataType::Decimal128(..) => {
                let array = column.as_any().downcast_ref::<array::Decimal128Array>().unwrap();
                // hugeint: d:38,0
                if array.scale() == 0 {
                    return ValueRef::HugeInt(array.value(row));
                }
                ValueRef::Decimal(Decimal::from_i128_with_scale(array.value(row), array.scale() as u32))
            }
            DataType::Timestamp(unit, _) if *unit == TimeUnit::Second => {
                let array = column.as_any().downcast_ref::<array::TimestampSecondArray>().unwrap();
                ValueRef::Timestamp(types::TimeUnit::Second, array.value(row))
            }
            DataType::Timestamp(unit, _) if *unit == TimeUnit::Millisecond => {
                let array = column
                    .as_any()
                    .downcast_ref::<array::TimestampMillisecondArray>()
                    .unwrap();
                ValueRef::Timestamp(types::TimeUnit::Millisecond, array.value(row))
            }
            DataType::Timestamp(unit, _) if *unit == TimeUnit::Microsecond => {
                let array = column
                    .as_any()
                    .downcast_ref::<array::TimestampMicrosecondArray>()
                    .unwrap();
                ValueRef::Timestamp(types::TimeUnit::Microsecond, array.value(row))
            }
            DataType::Timestamp(unit, _) if *unit == TimeUnit::Nanosecond => {
                let array = column
                    .as_any()
                    .downcast_ref::<array::TimestampNanosecondArray>()
                    .unwrap();
                ValueRef::Timestamp(types::TimeUnit::Nanosecond, array.value(row))
            }
            DataType::Date32 => {
                let array = column.as_any().downcast_ref::<array::Date32Array>().unwrap();
                ValueRef::Date32(array.value(row))
            }
            DataType::Time64(TimeUnit::Microsecond) => {
                let array = column.as_any().downcast_ref::<array::Time64MicrosecondArray>().unwrap();
                ValueRef::Time64(types::TimeUnit::Microsecond, array.value(row))
            }
            DataType::Interval(unit) => match unit {
                IntervalUnit::MonthDayNano => {
                    let array = column
                        .as_any()
                        .downcast_ref::<array::IntervalMonthDayNanoArray>()
                        .unwrap();
                    let value = array.value(row);

                    ValueRef::Interval {
                        months: value.months,
                        days: value.days,
                        nanos: value.nanoseconds,
                    }
                }
                _ => unimplemented!("{:?}", unit),
            },
            // TODO: support more data types
            // NOTE: DataTypes not supported by duckdb
            // DataType::Date64 => make_string_date!(array::Date64Array, column, row),
            // DataType::Time32(unit) if *unit == TimeUnit::Second => {
            //     make_string_time!(array::Time32SecondArray, column, row)
            // }
            // DataType::Time32(unit) if *unit == TimeUnit::Millisecond => {
            //     make_string_time!(array::Time32MillisecondArray, column, row)
            // }
            // DataType::Time64(unit) if *unit == TimeUnit::Nanosecond => {
            //     make_string_time!(array::Time64NanosecondArray, column, row)
            // }
            DataType::LargeList(..) => {
                let arr = column.as_any().downcast_ref::<array::LargeListArray>().unwrap();

                ValueRef::List(ListType::Large(arr), row)
            }
            DataType::List(..) => {
                let arr = column.as_any().downcast_ref::<ListArray>().unwrap();

                ValueRef::List(ListType::Regular(arr), row)
            }
            DataType::Dictionary(key_type, ..) => {
                let column = column.as_any();
                ValueRef::Enum(
                    match key_type.as_ref() {
                        DataType::UInt8 => {
                            EnumType::UInt8(column.downcast_ref::<DictionaryArray<UInt8Type>>().unwrap())
                        }
                        DataType::UInt16 => {
                            EnumType::UInt16(column.downcast_ref::<DictionaryArray<UInt16Type>>().unwrap())
                        }
                        DataType::UInt32 => {
                            EnumType::UInt32(column.downcast_ref::<DictionaryArray<UInt32Type>>().unwrap())
                        }
                        typ => panic!("Unsupported key type: {typ:?}"),
                    },
                    row,
                )
            }
            DataType::Struct(_) => {
                let res = column.as_any().downcast_ref::<StructArray>().unwrap();
                ValueRef::Struct(res, row)
            }
            DataType::Map(..) => {
                let arr = column.as_any().downcast_ref::<MapArray>().unwrap();
                ValueRef::Map(arr, row)
            }
            DataType::FixedSizeList(..) => {
                let arr = column.as_any().downcast_ref::<FixedSizeListArray>().unwrap();
                ValueRef::Array(arr, row)
            }
            DataType::Union(..) => ValueRef::Union(column, row),
            _ => unreachable!("invalid value: {}, {}", col, column.data_type()),
        }
    }

    /// Get the value of a particular column of the result row as a `ValueRef`,
    /// allowing data to be read out of a row without copying.
    ///
    /// This `ValueRef` is valid only as long as this Row, which is enforced by
    /// it's lifetime. This means that while this method is completely safe,
    /// it can be difficult to use, and most callers will be better served by
    /// [`get`](Row::get) or [`get_unwrap`](Row::get_unwrap).
    ///
    /// ## Failure
    ///
    /// Panics if calling [`row.get_ref(idx)`](Row::get_ref) would return an
    /// error, including:
    ///
    /// * If `idx` is outside the range of columns in the returned query.
    /// * If `idx` is not a valid column name for this row.
    pub fn get_ref_unwrap<I: RowIndex>(&self, idx: I) -> ValueRef<'_> {
        self.get_ref(idx).unwrap()
    }
}

impl<'stmt> AsRef<Statement<'stmt>> for Row<'stmt> {
    fn as_ref(&self) -> &Statement<'stmt> {
        self.stmt
    }
}

mod sealed {
    /// This trait exists just to ensure that the only impls of `trait Params`
    /// that are allowed are ones in this crate.
    pub trait Sealed {}
    impl Sealed for usize {}
    impl Sealed for &str {}
}

/// A trait implemented by types that can index into columns of a row.
///
/// It is only implemented for `usize` and `&str`.
pub trait RowIndex: sealed::Sealed {
    /// Returns the index of the appropriate column, or `None` if no such
    /// column exists.
    fn idx(&self, stmt: &Statement<'_>) -> Result<usize>;
}

impl RowIndex for usize {
    #[inline]
    fn idx(&self, stmt: &Statement<'_>) -> Result<usize> {
        if *self >= stmt.column_count() {
            Err(Error::InvalidColumnIndex(*self))
        } else {
            Ok(*self)
        }
    }
}

impl RowIndex for &'_ str {
    #[inline]
    fn idx(&self, stmt: &Statement<'_>) -> Result<usize> {
        stmt.column_index(self)
    }
}

macro_rules! tuple_try_from_row {
    ($($field:ident),*) => {
        impl<'a, $($field,)*> convert::TryFrom<&'a Row<'a>> for ($($field,)*) where $($field: FromSql,)* {
            type Error = crate::Error;

            // we end with index += 1, which rustc warns about
            // unused_variables and unused_mut are allowed for ()
            #[allow(unused_assignments, unused_variables, unused_mut)]
            fn try_from(row: &'a Row<'a>) -> Result<Self> {
                let mut index = 0;
                $(
                    #[allow(non_snake_case)]
                    let $field = row.get::<_, $field>(index)?;
                    index += 1;
                )*
                Ok(($($field,)*))
            }
        }
    }
}

macro_rules! tuples_try_from_row {
    () => {
        // not very useful, but maybe some other macro users will find this helpful
        tuple_try_from_row!();
    };
    ($first:ident $(, $remaining:ident)*) => {
        tuple_try_from_row!($first $(, $remaining)*);
        tuples_try_from_row!($($remaining),*);
    };
}

tuples_try_from_row!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

#[cfg(test)]
mod tests {
    #![allow(clippy::redundant_closure)] // false positives due to lifetime issues; clippy issue #5594
    use crate::{Connection, Result};

    #[test]
    fn test_try_from_row_for_tuple_1() -> Result<()> {
        use crate::ToSql;
        use std::convert::TryFrom;

        let conn = Connection::open_in_memory()?;
        conn.execute(
            "CREATE TABLE test (a INTEGER)",
            crate::params_from_iter(std::iter::empty::<&dyn ToSql>()),
        )?;
        conn.execute("INSERT INTO test VALUES (42)", [])?;
        let val = conn.query_row("SELECT a FROM test", [], |row| <(u32,)>::try_from(row))?;
        assert_eq!(val, (42,));
        let fail = conn.query_row("SELECT a FROM test", [], |row| <(u32, u32)>::try_from(row));
        assert!(fail.is_err());
        Ok(())
    }

    #[test]
    fn test_try_from_row_for_tuple_2() -> Result<()> {
        use std::convert::TryFrom;

        let conn = Connection::open_in_memory()?;
        conn.execute("CREATE TABLE test (a INTEGER, b INTEGER)", [])?;
        conn.execute("INSERT INTO test VALUES (42, 47)", [])?;
        let val = conn.query_row("SELECT a, b FROM test", [], |row| <(u32, u32)>::try_from(row))?;
        assert_eq!(val, (42, 47));
        let fail = conn.query_row("SELECT a, b FROM test", [], |row| <(u32, u32, u32)>::try_from(row));
        assert!(fail.is_err());
        Ok(())
    }

    #[test]
    fn test_try_from_row_for_tuple_16() -> Result<()> {
        use std::convert::TryFrom;

        let create_table = "CREATE TABLE test (
            a INTEGER,
            b INTEGER,
            c INTEGER,
            d INTEGER,
            e INTEGER,
            f INTEGER,
            g INTEGER,
            h INTEGER,
            i INTEGER,
            j INTEGER,
            k INTEGER,
            l INTEGER,
            m INTEGER,
            n INTEGER,
            o INTEGER,
            p INTEGER
        )";

        let insert_values = "INSERT INTO test VALUES (
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10,
            11,
            12,
            13,
            14,
            15
        )";

        type BigTuple = (
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
            u32,
        );

        let conn = Connection::open_in_memory()?;
        conn.execute(create_table, [])?;
        conn.execute(insert_values, [])?;
        let val = conn.query_row("SELECT * FROM test", [], |row| BigTuple::try_from(row))?;
        // Debug is not implemented for tuples of 16
        assert_eq!(val.0, 0);
        assert_eq!(val.1, 1);
        assert_eq!(val.2, 2);
        assert_eq!(val.3, 3);
        assert_eq!(val.4, 4);
        assert_eq!(val.5, 5);
        assert_eq!(val.6, 6);
        assert_eq!(val.7, 7);
        assert_eq!(val.8, 8);
        assert_eq!(val.9, 9);
        assert_eq!(val.10, 10);
        assert_eq!(val.11, 11);
        assert_eq!(val.12, 12);
        assert_eq!(val.13, 13);
        assert_eq!(val.14, 14);
        assert_eq!(val.15, 15);

        // We don't test one bigger because it's unimplemented
        Ok(())
    }

    #[test]
    #[cfg(feature = "vtab-arrow")]
    fn test_fixed_size_binary_via_arrow() -> Result<()> {
        use crate::vtab::arrow::{ArrowVTab, arrow_recordbatch_to_query_params};
        use arrow::array::{Array, ArrayRef, BinaryArray, FixedSizeBinaryArray};
        use arrow::datatypes::{DataType, Field, Schema};
        use arrow::record_batch::RecordBatch;
        use std::sync::Arc;

        let conn = Connection::open_in_memory()?;
        conn.register_table_function::<ArrowVTab>("arrow")?;

        // Create FixedSizeBinary(16) array - like UUID
        let values = vec![
            vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
            vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
            vec![0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255],
        ];

        let byte_array = FixedSizeBinaryArray::try_from_iter(values.into_iter()).unwrap();
        let arc: ArrayRef = Arc::new(byte_array);
        let schema = Schema::new(vec![Field::new("data", DataType::FixedSizeBinary(16), false)]);
        let batch = RecordBatch::try_new(Arc::new(schema), vec![arc]).unwrap();

        let mut stmt = conn.prepare("SELECT data FROM arrow(?, ?)")?;
        let mut arr = stmt.query_arrow(arrow_recordbatch_to_query_params(batch))?;
        let rb = arr.next().expect("no record batch");

        // DuckDB converts FixedSizeBinary to regular Binary
        let column = rb.column(0).as_any().downcast_ref::<BinaryArray>().unwrap();
        assert_eq!(column.len(), 3);
        assert_eq!(
            column.value(0),
            &[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
        );
        assert_eq!(
            column.value(1),
            &[16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        );
        assert_eq!(column.value(2), &[0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255]);

        Ok(())
    }

    #[test]
    #[cfg(feature = "vtab-arrow")]
    fn test_fixed_size_binary_with_nulls_via_arrow() -> Result<()> {
        use crate::vtab::arrow::{ArrowVTab, arrow_recordbatch_to_query_params};
        use arrow::array::{Array, ArrayRef, BinaryArray, FixedSizeBinaryArray};
        use arrow::datatypes::{DataType, Field, Schema};
        use arrow::record_batch::RecordBatch;
        use std::sync::Arc;

        let conn = Connection::open_in_memory()?;
        conn.register_table_function::<ArrowVTab>("arrow")?;

        // Create FixedSizeBinary(8) array with nulls
        let values = vec![
            Some(vec![1u8, 2, 3, 4, 5, 6, 7, 8]),
            None,
            Some(vec![9u8, 10, 11, 12, 13, 14, 15, 16]),
        ];

        let byte_array = FixedSizeBinaryArray::try_from_sparse_iter_with_size(values.into_iter(), 8).unwrap();
        let arc: ArrayRef = Arc::new(byte_array);
        let schema = Schema::new(vec![Field::new("data", DataType::FixedSizeBinary(8), true)]);
        let batch = RecordBatch::try_new(Arc::new(schema), vec![arc]).unwrap();

        let mut stmt = conn.prepare("SELECT data FROM arrow(?, ?)")?;
        let mut arr = stmt.query_arrow(arrow_recordbatch_to_query_params(batch))?;
        let rb = arr.next().expect("no record batch");

        // NOTE: Currently, null handling for FixedSizeBinary is not fully implemented
        // (see vtab/arrow.rs fixed_size_binary_array_to_vector, line 925-926)
        // Nulls are converted to zero bytes instead of actual nulls
        let column = rb.column(0).as_any().downcast_ref::<BinaryArray>().unwrap();
        assert_eq!(column.len(), 3);
        assert!(column.is_valid(0));
        // This should be false when null handling is implemented
        // assert!(!column.is_valid(1));
        assert!(column.is_valid(2));
        assert_eq!(column.value(0), &[1u8, 2, 3, 4, 5, 6, 7, 8]);
        // The null value is currently represented as zero bytes
        assert_eq!(column.value(1), &[0u8, 0, 0, 0, 0, 0, 0, 0]);
        assert_eq!(column.value(2), &[9u8, 10, 11, 12, 13, 14, 15, 16]);

        Ok(())
    }

    #[test]
    #[cfg(feature = "vtab-arrow")]
    fn test_fixed_size_binary_different_sizes_via_arrow() -> Result<()> {
        use crate::vtab::arrow::{ArrowVTab, arrow_recordbatch_to_query_params};
        use arrow::array::{ArrayRef, FixedSizeBinaryArray};
        use arrow::datatypes::{DataType, Field, Schema};
        use arrow::record_batch::RecordBatch;
        use std::sync::Arc;

        let conn = Connection::open_in_memory()?;
        conn.register_table_function::<ArrowVTab>("arrow")?;

        // Test with FixedSizeBinary(4)
        let values = vec![vec![1u8, 2, 3, 4], vec![5u8, 6, 7, 8]];

        let byte_array = FixedSizeBinaryArray::try_from_iter(values.into_iter()).unwrap();
        let arc: ArrayRef = Arc::new(byte_array);
        let schema = Schema::new(vec![Field::new("data", DataType::FixedSizeBinary(4), false)]);
        let batch = RecordBatch::try_new(Arc::new(schema), vec![arc]).unwrap();

        let mut stmt = conn.prepare("SELECT data FROM arrow(?, ?)")?;
        let mut rows = stmt.query(arrow_recordbatch_to_query_params(batch))?;

        // Read via Row interface
        let row = rows.next()?.unwrap();
        let bytes: Vec<u8> = row.get(0)?;
        assert_eq!(bytes, vec![1u8, 2, 3, 4]);

        let row = rows.next()?.unwrap();
        let bytes: Vec<u8> = row.get(0)?;
        assert_eq!(bytes, vec![5u8, 6, 7, 8]);

        Ok(())
    }

    #[test]
    #[cfg(feature = "vtab-arrow")]
    fn test_fixed_size_binary_value_ref_via_arrow() -> Result<()> {
        use crate::types::ValueRef;
        use crate::vtab::arrow::{ArrowVTab, arrow_recordbatch_to_query_params};
        use arrow::array::{ArrayRef, FixedSizeBinaryArray};
        use arrow::datatypes::{DataType, Field, Schema};
        use arrow::record_batch::RecordBatch;
        use std::sync::Arc;

        let conn = Connection::open_in_memory()?;
        conn.register_table_function::<ArrowVTab>("arrow")?;

        let values = vec![Some(vec![1u8, 2, 3, 4]), None];

        let byte_array = FixedSizeBinaryArray::try_from_sparse_iter_with_size(values.into_iter(), 4).unwrap();
        let arc: ArrayRef = Arc::new(byte_array);
        let schema = Schema::new(vec![Field::new("data", DataType::FixedSizeBinary(4), true)]);
        let batch = RecordBatch::try_new(Arc::new(schema), vec![arc]).unwrap();

        let mut stmt = conn.prepare("SELECT data FROM arrow(?, ?)")?;
        let mut rows = stmt.query(arrow_recordbatch_to_query_params(batch))?;

        // First row - non-null
        let row = rows.next()?.unwrap();
        let value_ref = row.get_ref(0)?;
        match value_ref {
            ValueRef::Blob(bytes) => {
                assert_eq!(bytes, &[1u8, 2, 3, 4]);
            }
            _ => panic!("Expected Blob ValueRef, got {:?}", value_ref),
        }

        // Second row - should be null, but currently null handling is not implemented
        // (see vtab/arrow.rs fixed_size_binary_array_to_vector, line 925-926)
        // so it's represented as zero bytes
        let row = rows.next()?.unwrap();
        let value_ref = row.get_ref(0)?;
        match value_ref {
            ValueRef::Blob(bytes) => {
                // This should be ValueRef::Null when null handling is implemented
                assert_eq!(bytes, &[0u8, 0, 0, 0]);
            }
            _ => panic!("Expected Blob ValueRef with zero bytes, got {:?}", value_ref),
        }

        Ok(())
    }

    #[cfg(feature = "uuid")]
    #[test]
    fn test_fixed_size_binary_uuid() -> Result<()> {
        use uuid::Uuid;

        let conn = Connection::open_in_memory()?;
        conn.execute_batch("CREATE TABLE test (id UUID)")?;

        let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
        conn.execute("INSERT INTO test VALUES (?)", [uuid_str])?;

        // Read back as UUID
        let uuid: Uuid = conn.query_row("SELECT id FROM test", [], |r| r.get(0))?;
        assert_eq!(uuid.to_string(), uuid_str);
        Ok(())
    }

    #[cfg(feature = "uuid")]
    #[test]
    fn test_fixed_size_binary_uuid_roundtrip() -> Result<()> {
        use uuid::Uuid;

        let conn = Connection::open_in_memory()?;
        conn.execute_batch("CREATE TABLE test (id UUID)")?;

        let original_uuid = Uuid::new_v4();
        conn.execute("INSERT INTO test VALUES (?)", [original_uuid])?;

        let retrieved_uuid: Uuid = conn.query_row("SELECT id FROM test", [], |r| r.get(0))?;
        assert_eq!(original_uuid, retrieved_uuid);
        Ok(())
    }
}