Skip to content

Commit 4a4203f

Browse files
authored
Show how to use Rows.and_then and point users to it (#560)
Fixes #384
2 parents 4faa961 + b46a91a commit 4a4203f

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

crates/duckdb/src/lib.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1238,6 +1238,32 @@ mod test {
12381238
}
12391239
Ok(())
12401240
}
1241+
1242+
#[test]
1243+
fn test_rows_and_then_with_custom_error() -> Result<()> {
1244+
let db = checked_memory_handle();
1245+
db.execute_batch("CREATE TABLE test (value INTEGER)")?;
1246+
db.execute_batch("INSERT INTO test VALUES (1), (3), (5)")?;
1247+
1248+
let mut stmt = db.prepare("SELECT value FROM test ORDER BY value")?;
1249+
let rows = stmt.query([])?;
1250+
1251+
// Use and_then to apply custom validation with custom error type
1252+
let results: Vec<i32> = rows
1253+
.and_then(|row| -> CustomResult<i32> {
1254+
let val: i32 = row.get(0)?; // duckdb::Error automatically converted via From trait
1255+
if val > 10 {
1256+
Err(CustomError::SomeError) // Custom application-specific error
1257+
} else {
1258+
Ok(val)
1259+
}
1260+
})
1261+
.collect::<CustomResult<Vec<_>>>()
1262+
.unwrap();
1263+
1264+
assert_eq!(results, vec![1, 3, 5]);
1265+
Ok(())
1266+
}
12411267
}
12421268

12431269
#[test]

crates/duckdb/src/row.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ impl<'stmt> Rows<'stmt> {
5858

5959
/// Map over this `Rows`, converting it to a [`Map`], which
6060
/// implements `FallibleIterator`.
61+
///
62+
/// **Note:** This method requires the closure to return `duckdb::Result<B>`.
63+
/// If you need to use custom error types, consider using [`and_then`](Self::and_then)
64+
/// instead, which allows any error type that implements `From<duckdb::Error>`.
65+
///
6166
/// ```rust,no_run
6267
/// use fallible_iterator::FallibleIterator;
6368
/// # use duckdb::{Result, Statement};

0 commit comments

Comments
 (0)