Merge pull request #1583 from gwenn/batch

Fix Batch impl
This commit is contained in:
gwenn 2024-10-18 20:30:50 +02:00 committed by GitHub
commit ea8563ee59
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 15 deletions

View File

@ -54,6 +54,8 @@
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
pub use fallible_iterator;
pub use fallible_streaming_iterator;
pub use libsqlite3_sys as ffi;
use std::cell::RefCell;
@ -1095,8 +1097,15 @@ impl fmt::Debug for Connection {
}
}
/// Batch iterator
/// Batch fallible iterator
///
/// # Warning
///
/// There is no recovery on parsing error, when a invalid statement is found in `sql`, SQLite cannot jump to the next statement.
/// So you should break the loop when an error is raised by the `next` method.
///
/// ```rust
/// use fallible_iterator::FallibleIterator;
/// use rusqlite::{Batch, Connection, Result};
///
/// fn main() -> Result<()> {
@ -1124,12 +1133,15 @@ impl<'conn, 'sql> Batch<'conn, 'sql> {
pub fn new(conn: &'conn Connection, sql: &'sql str) -> Self {
Batch { conn, sql, tail: 0 }
}
}
impl<'conn> fallible_iterator::FallibleIterator for Batch<'conn, '_> {
type Error = Error;
type Item = Statement<'conn>;
/// Iterates on each batch statements.
///
/// Returns `Ok(None)` when batch is completed.
#[expect(clippy::should_implement_trait)] // fallible iterator
pub fn next(&mut self) -> Result<Option<Statement<'conn>>> {
fn next(&mut self) -> Result<Option<Statement<'conn>>> {
while self.tail < self.sql.len() {
let sql = &self.sql[self.tail..];
let next = self.conn.prepare(sql)?;
@ -1148,14 +1160,6 @@ impl<'conn, 'sql> Batch<'conn, 'sql> {
}
}
impl<'conn> Iterator for Batch<'conn, '_> {
type Item = Result<Statement<'conn>>;
fn next(&mut self) -> Option<Result<Statement<'conn>>> {
self.next().transpose()
}
}
bitflags::bitflags! {
/// Flags for opening SQLite database connections. See
/// [sqlite3_open_v2](https://www.sqlite.org/c3ref/open.html) for details.
@ -2202,9 +2206,8 @@ mod test {
CREATE TABLE tbl1 (col);
CREATE TABLE tbl2 (col);
";
let batch = Batch::new(&db, sql);
for stmt in batch {
let mut stmt = stmt?;
let mut batch = Batch::new(&db, sql);
while let Some(mut stmt) = batch.next()? {
stmt.execute([])?;
}
Ok(())

View File

@ -5,7 +5,7 @@ use std::convert;
use super::{Error, Result, Statement};
use crate::types::{FromSql, FromSqlError, ValueRef};
/// A handle for the resulting rows of a query.
/// A handle (lazy fallible streaming iterator) 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>>,