duckdb / duckdb-rs

Ergonomic bindings to duckdb for Rust
MIT License
511 stars 113 forks source link

How to use the `column_count` method of Statement? #376

Open gmosx opened 3 months ago

gmosx commented 3 months ago

I am wondering, how is the column_count method supposed to be used.

AFAICU, you have to prepare and execute (query) the Statement, before you can call this method:

let mut stmt = conn.prepare(sql)?;
let mut rows = stmt.query([])?;
let column_count = stmt.column_count();

// IMPORTANT:
while let Some(row) = rows.next().unwrap() {
    ...
}

The problem is that the query* methods take a mutable reference to the Statement. When trying to call the column_count method, the borrow-checker complains:

cannot borrow `stmt` as immutable because it is also borrowed as mutable

Please note that the error is only triggered if the rows variable is actually used!

I would like to use the column count when 'deserializing' the rows. Any help/hints will be appreciated.

gmosx commented 2 months ago

Well, one solution is to 'collect' the rows variable and eliminate the ref to the Statement:

let records = rows.map(|r| ...);
let records = records.collect::<Vec<....>>().unwrap();

But this prohibits using the column_count in the 'deserialization code'.

gmosx commented 2 months ago

Actually you can use:

let col_count = rows.as_ref().unwrap().column_count();