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
#![allow(deprecated)]

use crate::frame::response::cql_to_rust::{FromRow, FromRowError};
use crate::frame::response::result::ColumnSpec;
use crate::frame::response::result::Row;
use scylla_cql::frame::frame_errors::ResultMetadataAndRowsCountParseError;
use scylla_cql::frame::response::result::{self, ResultMetadataHolder};
use scylla_cql::types::deserialize::{DeserializationError, TypeCheckError};
use thiserror::Error;
use uuid::Uuid;

/// Trait used to implement `Vec<result::Row>::into_typed<RowT>`
// This is the only way to add custom method to Vec
#[deprecated(
    since = "0.15.1",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
pub trait IntoTypedRows {
    fn into_typed<RowT: FromRow>(self) -> TypedRowIter<RowT>;
}

// Adds method Vec<result::Row>::into_typed<RowT>(self)
// It transforms the Vec into iterator mapping to custom row type
impl IntoTypedRows for Vec<result::Row> {
    fn into_typed<RowT: FromRow>(self) -> TypedRowIter<RowT> {
        TypedRowIter {
            row_iter: self.into_iter(),
            phantom_data: Default::default(),
        }
    }
}

/// Iterator over rows parsed as the given type\
/// Returned by `rows.into_typed::<(...)>()`
#[deprecated(
    since = "0.15.1",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
pub struct TypedRowIter<RowT: FromRow> {
    row_iter: std::vec::IntoIter<result::Row>,
    phantom_data: std::marker::PhantomData<RowT>,
}

impl<RowT: FromRow> Iterator for TypedRowIter<RowT> {
    type Item = Result<RowT, FromRowError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.row_iter.next().map(RowT::from_row)
    }
}

/// Result of a single query\
/// Contains all rows returned by the database and some more information
#[non_exhaustive]
#[derive(Default, Debug)]
#[deprecated(
    since = "0.15.0",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
pub struct LegacyQueryResult {
    /// Rows returned by the database.\
    /// Queries like `SELECT` will have `Some(Vec)`, while queries like `INSERT` will have `None`.\
    /// Can contain an empty Vec.
    pub rows: Option<Vec<Row>>,
    /// Warnings returned by the database
    pub warnings: Vec<String>,
    /// CQL Tracing uuid - can only be Some if tracing is enabled for this query
    pub tracing_id: Option<Uuid>,
    /// Metadata returned along with this response.
    pub(crate) metadata: Option<ResultMetadataHolder>,
    /// The original size of the serialized rows in request
    pub serialized_size: usize,
}

impl LegacyQueryResult {
    /// Returns the number of received rows.\
    /// Fails when the query isn't of a type that could return rows, same as [`rows()`](LegacyQueryResult::rows).
    pub fn rows_num(&self) -> Result<usize, RowsExpectedError> {
        match &self.rows {
            Some(rows) => Ok(rows.len()),
            None => Err(RowsExpectedError),
        }
    }

    /// Returns the received rows when present.\
    /// If `LegacyQueryResult.rows` is `None`, which means that this query is not supposed to return rows (e.g `INSERT`), returns an error.\
    /// Can return an empty `Vec`.
    pub fn rows(self) -> Result<Vec<Row>, RowsExpectedError> {
        match self.rows {
            Some(rows) => Ok(rows),
            None => Err(RowsExpectedError),
        }
    }

    /// Returns the received rows parsed as the given type.\
    /// Equal to `rows()?.into_typed()`.\
    /// Fails when the query isn't of a type that could return rows, same as [`rows()`](LegacyQueryResult::rows).
    pub fn rows_typed<RowT: FromRow>(self) -> Result<TypedRowIter<RowT>, RowsExpectedError> {
        Ok(self.rows()?.into_typed())
    }

    /// Returns `Ok` for a result of a query that shouldn't contain any rows.\
    /// Will return `Ok` for `INSERT` result, but a `SELECT` result, even an empty one, will cause an error.\
    /// Opposite of [`rows()`](LegacyQueryResult::rows).
    pub fn result_not_rows(&self) -> Result<(), RowsNotExpectedError> {
        match self.rows {
            Some(_) => Err(RowsNotExpectedError),
            None => Ok(()),
        }
    }

    /// Returns rows when `LegacyQueryResult.rows` is `Some`, otherwise an empty Vec.\
    /// Equal to `rows().unwrap_or_default()`.
    pub fn rows_or_empty(self) -> Vec<Row> {
        self.rows.unwrap_or_default()
    }

    /// Returns rows parsed as the given type.\
    /// When `LegacyQueryResult.rows` is `None`, returns 0 rows.\
    /// Equal to `rows_or_empty().into_typed::<RowT>()`.
    pub fn rows_typed_or_empty<RowT: FromRow>(self) -> TypedRowIter<RowT> {
        self.rows_or_empty().into_typed::<RowT>()
    }

    /// Returns first row from the received rows.\
    /// When the first row is not available, returns an error.
    pub fn first_row(self) -> Result<Row, FirstRowError> {
        match self.maybe_first_row()? {
            Some(row) => Ok(row),
            None => Err(FirstRowError::RowsEmpty),
        }
    }

    /// Returns first row from the received rows parsed as the given type.\
    /// When the first row is not available, returns an error.
    pub fn first_row_typed<RowT: FromRow>(self) -> Result<RowT, FirstRowTypedError> {
        Ok(self.first_row()?.into_typed()?)
    }

    /// Returns `Option<RowT>` containing the first of a result.\
    /// Fails when the query isn't of a type that could return rows, same as [`rows()`](LegacyQueryResult::rows).
    pub fn maybe_first_row(self) -> Result<Option<Row>, RowsExpectedError> {
        Ok(self.rows()?.into_iter().next())
    }

    /// Returns `Option<RowT>` containing the first of a result.\
    /// Fails when the query isn't of a type that could return rows, same as [`rows()`](LegacyQueryResult::rows).
    pub fn maybe_first_row_typed<RowT: FromRow>(
        self,
    ) -> Result<Option<RowT>, MaybeFirstRowTypedError> {
        match self.maybe_first_row()? {
            Some(row) => Ok(Some(row.into_typed::<RowT>()?)),
            None => Ok(None),
        }
    }

    /// Returns the only received row.\
    /// Fails if the result is anything else than a single row.\
    pub fn single_row(self) -> Result<Row, SingleRowError> {
        let rows: Vec<Row> = self.rows()?;

        if rows.len() != 1 {
            return Err(SingleRowError::BadNumberOfRows(rows.len()));
        }

        Ok(rows.into_iter().next().unwrap())
    }

    /// Returns the only received row parsed as the given type.\
    /// Fails if the result is anything else than a single row.\
    pub fn single_row_typed<RowT: FromRow>(self) -> Result<RowT, SingleRowTypedError> {
        Ok(self.single_row()?.into_typed::<RowT>()?)
    }

    /// Returns column specifications.
    #[inline]
    pub fn col_specs(&self) -> &[ColumnSpec<'_>] {
        self.metadata
            .as_ref()
            .map(|metadata| metadata.inner().col_specs())
            .unwrap_or_default()
    }

    /// Returns a column specification for a column with given name, or None if not found
    #[inline]
    pub fn get_column_spec<'a>(&'a self, name: &str) -> Option<(usize, &'a ColumnSpec<'a>)> {
        self.col_specs()
            .iter()
            .enumerate()
            .find(|(_id, spec)| spec.name() == name)
    }
}

/// An error that occurred during [`QueryResult`](crate::transport::query_result::QueryResult)
/// to [`LegacyQueryResult`] conversion.
#[deprecated(
    since = "0.15.1",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[non_exhaustive]
#[derive(Error, Clone, Debug)]
pub enum IntoLegacyQueryResultError {
    /// Failed to lazily deserialize result metadata.
    #[error("Failed to lazily deserialize result metadata: {0}")]
    ResultMetadataAndRowsCountParseError(#[from] ResultMetadataAndRowsCountParseError),

    /// Failed to perform the typecheck against [`Row`] type.
    #[error("Typecheck error: {0}")]
    TypecheckError(#[from] TypeCheckError),

    /// Failed to deserialize rows.
    #[error("Failed to deserialize rows: {0}")]
    DeserializationError(#[from] DeserializationError),
}

/// [`LegacyQueryResult::rows()`](LegacyQueryResult::rows) or a similar function called on a bad LegacyQueryResult.\
/// Expected `LegacyQueryResult.rows` to be `Some`, but it was `None`.\
/// `LegacyQueryResult.rows` is `Some` for queries that can return rows (e.g `SELECT`).\
/// It is `None` for queries that can't return rows (e.g `INSERT`).
#[deprecated(
    since = "0.15.1",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[error(
    "LegacyQueryResult::rows() or similar function called on a bad LegacyQueryResult.
         Expected LegacyQueryResult.rows to be Some, but it was None.
         LegacyQueryResult.rows is Some for queries that can return rows (e.g SELECT).
         It is None for queries that can't return rows (e.g INSERT)."
)]
pub struct RowsExpectedError;

/// [`LegacyQueryResult::result_not_rows()`](LegacyQueryResult::result_not_rows) called on a bad LegacyQueryResult.\
/// Expected `LegacyQueryResult.rows` to be `None`, but it was `Some`.\
/// `LegacyQueryResult.rows` is `Some` for queries that can return rows (e.g `SELECT`).\
/// It is `None` for queries that can't return rows (e.g `INSERT`).
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[error(
    "LegacyQueryResult::result_not_rows() called on a bad LegacyQueryResult.
         Expected LegacyQueryResult.rows to be None, but it was Some.
         LegacyQueryResult.rows is Some for queries that can return rows (e.g SELECT).
         It is None for queries that can't return rows (e.g INSERT)."
)]
pub struct RowsNotExpectedError;

#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum FirstRowError {
    /// [`LegacyQueryResult::first_row()`](LegacyQueryResult::first_row) called on a bad LegacyQueryResult.\
    /// Expected `LegacyQueryResult.rows` to be `Some`, but it was `None`.\
    /// `LegacyQueryResult.rows` is `Some` for queries that can return rows (e.g `SELECT`).\
    /// It is `None` for queries that can't return rows (e.g `INSERT`).
    #[error(transparent)]
    RowsExpected(#[from] RowsExpectedError),

    /// Rows in `LegacyQueryResult` are empty
    #[error("Rows in LegacyQueryResult are empty")]
    RowsEmpty,
}

#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum FirstRowTypedError {
    /// [`LegacyQueryResult::first_row_typed()`](LegacyQueryResult::first_row_typed) called on a bad LegacyQueryResult.\
    /// Expected `LegacyQueryResult.rows` to be `Some`, but it was `None`.\
    /// `LegacyQueryResult.rows` is `Some` for queries that can return rows (e.g `SELECT`).\
    /// It is `None` for queries that can't return rows (e.g `INSERT`).
    #[error(transparent)]
    RowsExpected(#[from] RowsExpectedError),

    /// Rows in `LegacyQueryResult` are empty
    #[error("Rows in LegacyQueryResult are empty")]
    RowsEmpty,

    /// Parsing row as the given type failed
    #[error(transparent)]
    FromRowError(#[from] FromRowError),
}

#[deprecated(
    since = "0.15.1",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum MaybeFirstRowTypedError {
    /// [`LegacyQueryResult::maybe_first_row_typed()`](LegacyQueryResult::maybe_first_row_typed) called on a bad LegacyQueryResult.\
    /// Expected `LegacyQueryResult.rows` to be `Some`, but it was `None`.
    /// `LegacyQueryResult.rows` is `Some` for queries that can return rows (e.g `SELECT`).\
    /// It is `None` for queries that can't return rows (e.g `INSERT`).
    #[error(transparent)]
    RowsExpected(#[from] RowsExpectedError),

    /// Parsing row as the given type failed
    #[error(transparent)]
    FromRowError(#[from] FromRowError),
}

#[deprecated(
    since = "0.15.1",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum SingleRowError {
    /// [`LegacyQueryResult::single_row()`](LegacyQueryResult::single_row) called on a bad LegacyQueryResult.\
    /// Expected `LegacyQueryResult.rows` to be `Some`, but it was `None`.\
    /// `LegacyQueryResult.rows` is `Some` for queries that can return rows (e.g `SELECT`).\
    /// It is `None` for queries that can't return rows (e.g `INSERT`).
    #[error(transparent)]
    RowsExpected(#[from] RowsExpectedError),

    /// Expected a single row, found other number of rows
    #[error("Expected a single row, found {0} rows")]
    BadNumberOfRows(usize),
}

#[deprecated(
    since = "0.15.1",
    note = "Legacy deserialization API is inefficient and is going to be removed soon"
)]
#[allow(deprecated)]
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum SingleRowTypedError {
    /// [`LegacyQueryResult::single_row_typed()`](LegacyQueryResult::single_row_typed) called on a bad LegacyQueryResult.\
    /// Expected `LegacyQueryResult.rows` to be `Some`, but it was `None`.\
    /// `LegacyQueryResult.rows` is `Some` for queries that can return rows (e.g `SELECT`).\
    /// It is `None` for queries that can't return rows (e.g `INSERT`).
    #[error(transparent)]
    RowsExpected(#[from] RowsExpectedError),

    /// Expected a single row, found other number of rows
    #[error("Expected a single row, found {0} rows")]
    BadNumberOfRows(usize),

    /// Parsing row as the given type failed
    #[error(transparent)]
    FromRowError(#[from] FromRowError),
}

impl From<FirstRowError> for FirstRowTypedError {
    fn from(err: FirstRowError) -> FirstRowTypedError {
        match err {
            FirstRowError::RowsExpected(e) => FirstRowTypedError::RowsExpected(e),
            FirstRowError::RowsEmpty => FirstRowTypedError::RowsEmpty,
        }
    }
}

impl From<SingleRowError> for SingleRowTypedError {
    fn from(err: SingleRowError) -> SingleRowTypedError {
        match err {
            SingleRowError::RowsExpected(e) => SingleRowTypedError::RowsExpected(e),
            SingleRowError::BadNumberOfRows(r) => SingleRowTypedError::BadNumberOfRows(r),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        frame::response::result::{CqlValue, Row},
        test_utils::setup_tracing,
    };
    use std::convert::TryInto;
    use std::sync::Arc;

    use assert_matches::assert_matches;
    use scylla_cql::frame::response::result::{ColumnType, ResultMetadata, TableSpec};

    // Returns specified number of rows, each one containing one int32 value.
    // Values are 0, 1, 2, 3, 4, ...
    fn make_rows(rows_num: usize) -> Vec<Row> {
        let mut rows: Vec<Row> = Vec::with_capacity(rows_num);
        for cur_value in 0..rows_num {
            let int_val: i32 = cur_value.try_into().unwrap();
            rows.push(Row {
                columns: vec![Some(CqlValue::Int(int_val))],
            });
        }
        rows
    }

    // Just like make_rows, but each column has one String value
    // values are "val0", "val1", "val2", ...
    fn make_string_rows(rows_num: usize) -> Vec<Row> {
        let mut rows: Vec<Row> = Vec::with_capacity(rows_num);
        for cur_value in 0..rows_num {
            rows.push(Row {
                columns: vec![Some(CqlValue::Text(format!("val{}", cur_value)))],
            });
        }
        rows
    }

    fn make_test_metadata() -> ResultMetadata<'static> {
        let table_spec = TableSpec::borrowed("some_keyspace", "some_table");

        let column_spec = ColumnSpec::borrowed("column0", ColumnType::Int, table_spec);

        ResultMetadata::new_for_test(1, vec![column_spec])
    }

    fn make_not_rows_query_result() -> LegacyQueryResult {
        LegacyQueryResult {
            rows: None,
            warnings: vec![],
            tracing_id: None,
            metadata: None,
            serialized_size: 0,
        }
    }

    fn make_rows_query_result(rows_num: usize) -> LegacyQueryResult {
        let mut res = make_not_rows_query_result();
        res.rows = Some(make_rows(rows_num));
        res.metadata = Some(ResultMetadataHolder::SharedCached(Arc::new(
            make_test_metadata(),
        )));
        res
    }

    fn make_string_rows_query_result(rows_num: usize) -> LegacyQueryResult {
        let mut res = make_not_rows_query_result();
        res.rows = Some(make_string_rows(rows_num));
        res.metadata = Some(ResultMetadataHolder::SharedCached(Arc::new(
            make_test_metadata(),
        )));
        res
    }

    #[test]
    fn rows_num_test() {
        setup_tracing();
        assert_eq!(
            make_not_rows_query_result().rows_num(),
            Err(RowsExpectedError)
        );
        assert_eq!(make_rows_query_result(0).rows_num(), Ok(0));
        assert_eq!(make_rows_query_result(1).rows_num(), Ok(1));
        assert_eq!(make_rows_query_result(2).rows_num(), Ok(2));
        assert_eq!(make_rows_query_result(3).rows_num(), Ok(3));
    }

    #[test]
    fn rows_test() {
        setup_tracing();
        assert_eq!(make_not_rows_query_result().rows(), Err(RowsExpectedError));
        assert_eq!(make_rows_query_result(0).rows(), Ok(vec![]));
        assert_eq!(make_rows_query_result(1).rows(), Ok(make_rows(1)));
        assert_eq!(make_rows_query_result(2).rows(), Ok(make_rows(2)));
    }

    #[test]
    fn rows_typed_test() {
        setup_tracing();
        assert!(make_not_rows_query_result().rows_typed::<(i32,)>().is_err());

        let rows0: Vec<(i32,)> = make_rows_query_result(0)
            .rows_typed::<(i32,)>()
            .unwrap()
            .map(|r| r.unwrap())
            .collect();

        assert_eq!(rows0, vec![]);

        let rows1: Vec<(i32,)> = make_rows_query_result(1)
            .rows_typed::<(i32,)>()
            .unwrap()
            .map(|r| r.unwrap())
            .collect();

        assert_eq!(rows1, vec![(0,)]);

        let rows2: Vec<(i32,)> = make_rows_query_result(2)
            .rows_typed::<(i32,)>()
            .unwrap()
            .map(|r| r.unwrap())
            .collect();

        assert_eq!(rows2, vec![(0,), (1,)]);
    }

    #[test]
    fn result_not_rows_test() {
        setup_tracing();
        assert_eq!(make_not_rows_query_result().result_not_rows(), Ok(()));
        assert_eq!(
            make_rows_query_result(0).result_not_rows(),
            Err(RowsNotExpectedError)
        );
        assert_eq!(
            make_rows_query_result(1).result_not_rows(),
            Err(RowsNotExpectedError)
        );
        assert_eq!(
            make_rows_query_result(2).result_not_rows(),
            Err(RowsNotExpectedError)
        );
    }

    #[test]
    fn rows_or_empty_test() {
        setup_tracing();
        assert_eq!(make_not_rows_query_result().rows_or_empty(), vec![]);
        assert_eq!(make_rows_query_result(0).rows_or_empty(), make_rows(0));
        assert_eq!(make_rows_query_result(1).rows_or_empty(), make_rows(1));
        assert_eq!(make_rows_query_result(2).rows_or_empty(), make_rows(2));
    }

    #[test]
    fn rows_typed_or_empty() {
        setup_tracing();
        let rows_empty: Vec<(i32,)> = make_not_rows_query_result()
            .rows_typed_or_empty::<(i32,)>()
            .map(|r| r.unwrap())
            .collect();

        assert_eq!(rows_empty, vec![]);

        let rows0: Vec<(i32,)> = make_rows_query_result(0)
            .rows_typed_or_empty::<(i32,)>()
            .map(|r| r.unwrap())
            .collect();

        assert_eq!(rows0, vec![]);

        let rows1: Vec<(i32,)> = make_rows_query_result(1)
            .rows_typed_or_empty::<(i32,)>()
            .map(|r| r.unwrap())
            .collect();

        assert_eq!(rows1, vec![(0,)]);

        let rows2: Vec<(i32,)> = make_rows_query_result(2)
            .rows_typed_or_empty::<(i32,)>()
            .map(|r| r.unwrap())
            .collect();

        assert_eq!(rows2, vec![(0,), (1,)]);
    }

    #[test]
    fn first_row_test() {
        setup_tracing();
        assert_eq!(
            make_not_rows_query_result().first_row(),
            Err(FirstRowError::RowsExpected(RowsExpectedError))
        );
        assert_eq!(
            make_rows_query_result(0).first_row(),
            Err(FirstRowError::RowsEmpty)
        );
        assert_eq!(
            make_rows_query_result(1).first_row(),
            Ok(make_rows(1).into_iter().next().unwrap())
        );
        assert_eq!(
            make_rows_query_result(2).first_row(),
            Ok(make_rows(2).into_iter().next().unwrap())
        );
        assert_eq!(
            make_rows_query_result(3).first_row(),
            Ok(make_rows(3).into_iter().next().unwrap())
        );
    }

    #[test]
    fn first_row_typed_test() {
        setup_tracing();
        assert_eq!(
            make_not_rows_query_result().first_row_typed::<(i32,)>(),
            Err(FirstRowTypedError::RowsExpected(RowsExpectedError))
        );
        assert_eq!(
            make_rows_query_result(0).first_row_typed::<(i32,)>(),
            Err(FirstRowTypedError::RowsEmpty)
        );
        assert_eq!(
            make_rows_query_result(1).first_row_typed::<(i32,)>(),
            Ok((0,))
        );
        assert_eq!(
            make_rows_query_result(2).first_row_typed::<(i32,)>(),
            Ok((0,))
        );
        assert_eq!(
            make_rows_query_result(3).first_row_typed::<(i32,)>(),
            Ok((0,))
        );

        assert_matches!(
            make_string_rows_query_result(2).first_row_typed::<(i32,)>(),
            Err(FirstRowTypedError::FromRowError(_))
        );
    }

    #[test]
    fn maybe_first_row_test() {
        setup_tracing();
        assert_eq!(
            make_not_rows_query_result().maybe_first_row(),
            Err(RowsExpectedError)
        );
        assert_eq!(make_rows_query_result(0).maybe_first_row(), Ok(None));
        assert_eq!(
            make_rows_query_result(1).maybe_first_row(),
            Ok(Some(make_rows(1).into_iter().next().unwrap()))
        );
        assert_eq!(
            make_rows_query_result(2).maybe_first_row(),
            Ok(Some(make_rows(2).into_iter().next().unwrap()))
        );
        assert_eq!(
            make_rows_query_result(3).maybe_first_row(),
            Ok(Some(make_rows(3).into_iter().next().unwrap()))
        );
    }

    #[test]
    fn maybe_first_row_typed_test() {
        setup_tracing();
        assert_eq!(
            make_not_rows_query_result().maybe_first_row_typed::<(i32,)>(),
            Err(MaybeFirstRowTypedError::RowsExpected(RowsExpectedError))
        );

        assert_eq!(
            make_rows_query_result(0).maybe_first_row_typed::<(i32,)>(),
            Ok(None)
        );

        assert_eq!(
            make_rows_query_result(1).maybe_first_row_typed::<(i32,)>(),
            Ok(Some((0,)))
        );

        assert_eq!(
            make_rows_query_result(2).maybe_first_row_typed::<(i32,)>(),
            Ok(Some((0,)))
        );

        assert_eq!(
            make_rows_query_result(3).maybe_first_row_typed::<(i32,)>(),
            Ok(Some((0,)))
        );

        assert_matches!(
            make_string_rows_query_result(1).maybe_first_row_typed::<(i32,)>(),
            Err(MaybeFirstRowTypedError::FromRowError(_))
        )
    }

    #[test]
    fn single_row_test() {
        setup_tracing();
        assert_eq!(
            make_not_rows_query_result().single_row(),
            Err(SingleRowError::RowsExpected(RowsExpectedError))
        );
        assert_eq!(
            make_rows_query_result(0).single_row(),
            Err(SingleRowError::BadNumberOfRows(0))
        );
        assert_eq!(
            make_rows_query_result(1).single_row(),
            Ok(make_rows(1).into_iter().next().unwrap())
        );
        assert_eq!(
            make_rows_query_result(2).single_row(),
            Err(SingleRowError::BadNumberOfRows(2))
        );
        assert_eq!(
            make_rows_query_result(3).single_row(),
            Err(SingleRowError::BadNumberOfRows(3))
        );
    }

    #[test]
    fn single_row_typed_test() {
        setup_tracing();
        assert_eq!(
            make_not_rows_query_result().single_row_typed::<(i32,)>(),
            Err(SingleRowTypedError::RowsExpected(RowsExpectedError))
        );
        assert_eq!(
            make_rows_query_result(0).single_row_typed::<(i32,)>(),
            Err(SingleRowTypedError::BadNumberOfRows(0))
        );
        assert_eq!(
            make_rows_query_result(1).single_row_typed::<(i32,)>(),
            Ok((0,))
        );
        assert_eq!(
            make_rows_query_result(2).single_row_typed::<(i32,)>(),
            Err(SingleRowTypedError::BadNumberOfRows(2))
        );
        assert_eq!(
            make_rows_query_result(3).single_row_typed::<(i32,)>(),
            Err(SingleRowTypedError::BadNumberOfRows(3))
        );

        assert_matches!(
            make_string_rows_query_result(1).single_row_typed::<(i32,)>(),
            Err(SingleRowTypedError::FromRowError(_))
        );
    }
}