Simplify Rust API verbosity by implementing Row.get() and

Statement.query_row()
This commit is contained in:
Diego Reis
2025-07-31 16:08:06 -03:00
parent adb81dd6ce
commit 572d3bd4ce
3 changed files with 42 additions and 33 deletions

View File

@@ -61,6 +61,10 @@ pub enum Error {
SqlExecutionFailure(String),
#[error("WAL operation error: `{0}`")]
WalOperationError(String),
#[error("Query returned no rows")]
QueryReturnedNoRows,
#[error("Conversion failure: `{0}`")]
ConversionFailure(String),
}
impl From<turso_core::LimboError> for Error {
@@ -422,6 +426,17 @@ impl Statement {
let mut stmt = self.inner.lock().unwrap();
stmt.reset();
}
/// Execute a query that returns the first [`Row`].
///
/// # Errors
///
/// - Returns `QueryReturnedNoRows` if no rows were returned.
pub async fn query_row(&mut self, params: impl IntoParams) -> Result<Row> {
let mut rows = self.query(params).await?;
rows.next().await?.ok_or(Error::QueryReturnedNoRows)
}
}
/// Column information.

View File

@@ -79,6 +79,14 @@ impl Row {
}
}
pub fn get<T>(&self, idx: usize) -> Result<T>
where
T: FromValue,
{
let val = &self.values[idx];
T::from_sql(val.clone()).map_err(|err| Error::ConversionFailure(err.to_string()))
}
pub fn column_count(&self) -> usize {
self.values.len()
}

View File

@@ -344,17 +344,13 @@ mod test {
}
{
let tx = conn.transaction().await?;
let mut result = tx.query("SELECT SUM(x) FROM foo", ()).await?;
assert_eq!(
2,
*result
.next()
.await?
.unwrap()
.get_value(0)?
.as_integer()
.unwrap()
);
let result = tx
.prepare("SELECT SUM(x) FROM foo")
.await?
.query_row(())
.await?;
assert_eq!(2, result.get::<i32>(0)?);
tx.finish().await?;
}
Ok(())
@@ -390,17 +386,12 @@ mod test {
tx.commit().await?;
}
let mut result = conn.query("SELECT SUM(x) FROM foo", ()).await?;
assert_eq!(
2,
*result
.next()
.await?
.unwrap()
.get_value(0)?
.as_integer()
.unwrap()
);
let result = conn
.prepare("SELECT SUM(x) FROM foo")
.await?
.query_row(())
.await?;
assert_eq!(2, result.get::<i32>(0)?);
Ok(())
}
@@ -425,17 +416,12 @@ mod test {
tx.commit().await?;
}
{
let mut result = conn.query("SELECT SUM(x) FROM foo", ()).await?;
assert_eq!(
6,
*result
.next()
.await?
.unwrap()
.get_value(0)?
.as_integer()
.unwrap()
);
let result = conn
.prepare("SELECT SUM(x) FROM foo")
.await?
.query_row(())
.await?;
assert_eq!(6, result.get::<i32>(0)?);
}
Ok(())
}