Skip to content

Migrate errors from anyhow to libsql::Error #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "libsql-client"
version = "0.31.11"
version = "0.32.0"
edition = "2021"
license = "Apache-2.0"
description = "HTTP-based client for libSQL and sqld"
Expand All @@ -19,7 +19,6 @@ spin-sdk = { version = "1.4", git = "https://github.com/fermyon/spin", tag = "v1
sqlite3-parser = { version = "0.8.0", default-features = false, features = [ "YYNOERRORRECOVERY" ] }
http = { version = "0.2", optional = true }
bytes = { version = "1.4.0", optional = true }
anyhow = "1.0.69"
reqwest = { version = "0.11.14", optional = true, default-features = false, features = ["rustls-tls"] }
hrana-client = { version = "0.3", optional = true }
hrana-client-proto = { version = "0.2" }
Expand All @@ -28,13 +27,13 @@ serde = "1.0.159"
tracing = "0.1.37"
futures = "0.3.28"
fallible-iterator = "0.2.0"
libsql = { version = "0.1.6", optional = true }
libsql = { version = "0.1.11", default-features = false }

[features]
default = ["local_backend", "hrana_backend", "reqwest_backend", "mapping_names_to_values_in_rows"]
workers_backend = ["worker", "futures-util"]
reqwest_backend = ["reqwest"]
local_backend = ["libsql"]
local_backend = ["libsql/core", "libsql/replication"]
spin_backend = ["spin-sdk", "http", "bytes"]
hrana_backend = ["hrana-client"]
separate_url_for_queries = []
Expand Down
2 changes: 1 addition & 1 deletion examples/connect_from_config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::Result;
use libsql_client::Result;
use libsql_client::{args, Client, ResultSet, Statement};
use rand::prelude::SliceRandom;

Expand Down
2 changes: 1 addition & 1 deletion examples/connect_from_env.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::Result;
use libsql_client::Result;
use libsql_client::{args, Client, ResultSet, Statement};
use rand::prelude::SliceRandom;

Expand Down
4 changes: 2 additions & 2 deletions examples/select.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::Result;
use libsql_client::Result;
use libsql_client::{args, de, Client, Statement};
use rand::prelude::SliceRandom;

Expand Down Expand Up @@ -70,7 +70,7 @@ async fn bump_counter(db: Client) -> Result<String> {
.rows
.iter()
.map(de::from_row)
.collect::<Result<Vec<Counter>, _>>()?;
.collect::<Result<Vec<Counter>>>()?;

let scoreboard = result_to_string(counter_response)?;
let html = format!("Scoreboard:\n{scoreboard}");
Expand Down
50 changes: 26 additions & 24 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! [Client] is the main structure to interact with the database.
use anyhow::Result;

use crate::{proto, BatchResult, ResultSet, Statement, SyncTransaction, Transaction};
use crate::{
proto, BatchResult, Error, Result, ResultSet, Statement, SyncTransaction, Transaction,
};

static TRANSACTION_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

Expand Down Expand Up @@ -57,7 +57,7 @@ impl Client {
) -> Result<BatchResult> {
match self {
#[cfg(feature = "local_backend")]
Self::Local(l) => l.raw_batch(stmts),
Self::Local(l) => l.raw_batch(stmts).await,
#[cfg(any(
feature = "reqwest_backend",
feature = "workers_backend",
Expand Down Expand Up @@ -111,7 +111,7 @@ impl Client {
.find(|e| e.is_some())
.flatten();
if let Some(error) = step_error {
return Err(anyhow::anyhow!(error.message));
return Err(Error::Misuse(error.message));
}
let mut step_results: Vec<Result<ResultSet>> = batch_results
.step_results
Expand All @@ -120,7 +120,7 @@ impl Client {
.map(|maybe_rs| {
maybe_rs
.map(ResultSet::from)
.ok_or_else(|| anyhow::anyhow!("Unexpected missing result set"))
.ok_or_else(|| Error::Misuse("Unexpected missing result set".into()))
})
.collect();
step_results.pop(); // END is not counted in the result, it's implicitly ignored
Expand Down Expand Up @@ -179,7 +179,7 @@ impl Client {
pub async fn execute(&self, stmt: impl Into<Statement> + Send) -> Result<ResultSet> {
match self {
#[cfg(feature = "local_backend")]
Self::Local(l) => l.execute(stmt),
Self::Local(l) => l.execute(stmt).await,
#[cfg(any(
feature = "reqwest_backend",
feature = "workers_backend",
Expand Down Expand Up @@ -218,7 +218,7 @@ impl Client {
) -> Result<ResultSet> {
match self {
#[cfg(feature = "local_backend")]
Self::Local(l) => l.execute_in_transaction(tx_id, stmt),
Self::Local(l) => l.execute_in_transaction(tx_id, stmt).await,
#[cfg(any(
feature = "reqwest_backend",
feature = "workers_backend",
Expand All @@ -235,7 +235,7 @@ impl Client {
pub(crate) async fn commit_transaction(&self, tx_id: u64) -> Result<()> {
match self {
#[cfg(feature = "local_backend")]
Self::Local(l) => l.commit_transaction(tx_id),
Self::Local(l) => l.commit_transaction(tx_id).await,
#[cfg(any(
feature = "reqwest_backend",
feature = "workers_backend",
Expand All @@ -252,7 +252,7 @@ impl Client {
pub(crate) async fn rollback_transaction(&self, tx_id: u64) -> Result<()> {
match self {
#[cfg(feature = "local_backend")]
Self::Local(l) => l.rollback_transaction(tx_id),
Self::Local(l) => l.rollback_transaction(tx_id).await,
#[cfg(any(
feature = "reqwest_backend",
feature = "workers_backend",
Expand All @@ -279,7 +279,7 @@ impl Client {
/// # }
/// ```
#[cfg(feature = "local_backend")]
pub fn in_memory() -> anyhow::Result<Client> {
pub fn in_memory() -> Result<Client> {
Ok(Client::Local(crate::local::Client::in_memory()?))
}

Expand All @@ -298,7 +298,7 @@ impl Client {
/// # }
/// ```
#[allow(unreachable_patterns)]
pub async fn from_config<'a>(mut config: Config) -> anyhow::Result<Client> {
pub async fn from_config<'a>(mut config: Config) -> Result<Client> {
config.url = if config.url.scheme() == "libsql" {
// We cannot use url::Url::set_scheme() because it prevents changing the scheme to http...
// Safe to unwrap, because we know that the scheme is libsql
Expand Down Expand Up @@ -331,7 +331,7 @@ impl Client {
let inner = crate::http::InnerClient::Spin(crate::spin::HttpClient::new());
Client::Http(crate::http::Client::from_config(inner, config)?)
},
_ => anyhow::bail!("Unknown scheme: {scheme}. Make sure your backend exists and is enabled with its feature flag"),
_ => return Err(Error::Misuse(format!("Unknown scheme: {scheme}. Make sure your backend exists and is enabled with its feature flag"))),
})
}

Expand All @@ -352,30 +352,32 @@ impl Client {
/// let db = libsql_client::Client::from_env().await.unwrap();
/// # }
/// ```
pub async fn from_env() -> anyhow::Result<Client> {
pub async fn from_env() -> Result<Client> {
let url = std::env::var("LIBSQL_CLIENT_URL").map_err(|_| {
anyhow::anyhow!("LIBSQL_CLIENT_URL variable should point to your libSQL/sqld database")
Error::Misuse(
"LIBSQL_CLIENT_URL variable should point to your libSQL/sqld database".into(),
)
})?;
let auth_token = std::env::var("LIBSQL_CLIENT_TOKEN").ok();
Self::from_config(Config {
url: url::Url::parse(&url)?,
url: url::Url::parse(&url).map_err(|e| Error::Misuse(e.to_string()))?,
auth_token,
})
.await
}

#[cfg(feature = "workers_backend")]
pub fn from_workers_env(env: &worker::Env) -> anyhow::Result<Client> {
pub fn from_workers_env(env: &worker::Env) -> Result<Client> {
let url = env
.secret("LIBSQL_CLIENT_URL")
.map_err(|e| anyhow::anyhow!("{e}"))?
.map_err(|e| Error::Misuse(e.to_string()))?
.to_string();
let token = env
.secret("LIBSQL_CLIENT_TOKEN")
.map_err(|e| anyhow::anyhow!("{e}"))?
.map_err(|e| Error::Misuse(e.to_string()))?
.to_string();
let config = Config {
url: url::Url::parse(&url)?,
url: url::Url::parse(&url).map_err(|e| Error::Misuse(e.to_string()))?,
auth_token: Some(token),
};
let inner = crate::http::InnerClient::Workers(crate::workers::HttpClient::new());
Expand All @@ -398,7 +400,7 @@ impl SyncClient {
/// # }
/// ```
#[cfg(feature = "local_backend")]
pub fn in_memory() -> anyhow::Result<Self> {
pub fn in_memory() -> Result<Self> {
Ok(Self {
inner: Client::in_memory()?,
})
Expand Down Expand Up @@ -570,7 +572,7 @@ impl Config {
/// # Examples
///
/// ```
/// # async fn f() -> anyhow::Result<()> {
/// # async fn f() -> libsql_client::Result<()> {
/// # use libsql_client::Config;
/// let config = Config::new("file:////tmp/example.db")?;
/// let db = libsql_client::Client::from_config(config).await.unwrap();
Expand All @@ -584,7 +586,7 @@ impl Config {
Ok(Self {
url: url
.try_into()
.map_err(|e| anyhow::anyhow!("Failed to parse url: {}", e))?,
.map_err(|e| Error::Misuse(format!("Failed to parse url: {e}")))?,
auth_token: None,
})
}
Expand All @@ -593,7 +595,7 @@ impl Config {
/// # Examples
///
/// ```
/// # async fn f() -> anyhow::Result<()> {
/// # async fn f() -> libsql_client::Result<()> {
/// # use libsql_client::Config;
/// let config = Config::new("https://example.com/db")?.with_auth_token("secret");
/// let db = libsql_client::Client::from_config(config).await.unwrap();
Expand Down
6 changes: 3 additions & 3 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::Row;
/// # Example
///
/// ```no_run
/// # async fn run(db: libsql_client::Client) -> anyhow::Result<()> {
/// # async fn run(db: libsql_client::Client) -> libsql_client::Result<()> {
/// use libsql_client::de;
///
/// #[derive(Debug, serde::Deserialize)]
Expand All @@ -49,9 +49,9 @@ use crate::Row;
/// # Ok(())
/// # }
/// ```
pub fn from_row<'de, T: Deserialize<'de>>(row: &'de Row) -> anyhow::Result<T> {
pub fn from_row<'de, T: Deserialize<'de>>(row: &'de Row) -> crate::Result<T> {
let de = De { row };
T::deserialize(de).map_err(Into::into)
T::deserialize(de).map_err(|e| crate::Error::Misuse(e.to_string()))
}

struct De<'de> {
Expand Down
Loading