1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use async_trait::async_trait;
use anyhow::Result;
use super::{parse_query_result, QueryResult, Statement};
#[async_trait(?Send)]
pub trait Connection {
async fn execute(&self, stmt: impl Into<Statement>) -> Result<QueryResult> {
let mut results = self.batch(std::iter::once(stmt)).await?;
Ok(results.remove(0))
}
async fn batch(
&self,
stmts: impl IntoIterator<Item = impl Into<Statement>>,
) -> Result<Vec<QueryResult>>;
async fn transaction(
&self,
stmts: impl IntoIterator<Item = impl Into<Statement>>,
) -> Result<Vec<QueryResult>> {
let mut ret: Vec<QueryResult> = self
.batch(
std::iter::once(Statement::new("BEGIN"))
.chain(stmts.into_iter().map(|s| s.into()))
.chain(std::iter::once(Statement::new("END"))),
)
.await?
.into_iter()
.skip(1)
.collect();
ret.pop();
Ok(ret)
}
}
pub enum GenericConnection {
#[cfg(feature = "local_backend")]
Local(super::local::Connection),
#[cfg(feature = "reqwest_backend")]
Reqwest(super::reqwest::Connection),
#[cfg(feature = "workers_backend")]
Workers(super::workers::Connection),
}
#[async_trait(?Send)]
impl Connection for GenericConnection {
async fn batch(
&self,
stmts: impl IntoIterator<Item = impl Into<Statement>>,
) -> Result<Vec<QueryResult>> {
match self {
#[cfg(feature = "local_backend")]
Self::Local(l) => l.batch(stmts).await,
#[cfg(feature = "reqwest_backend")]
Self::Reqwest(r) => r.batch(stmts).await,
#[cfg(feature = "workers_backend")]
Self::Workers(w) => w.batch(stmts).await,
}
}
}
pub fn connect() -> anyhow::Result<GenericConnection> {
let url = std::env::var("LIBSQL_CLIENT_URL").map_err(|_| {
anyhow::anyhow!("LIBSQL_CLIENT_URL variable should point to your libSQL/sqld database")
})?;
let backend = std::env::var("LIBSQL_CLIENT_BACKEND").unwrap_or_else(|_| {
if url.starts_with("http") {
return if cfg!(feature = "reqwest_backend") {
"reqwest"
} else if cfg!(feature = "workers_backend") {
"workers"
} else {
"local"
}
.to_string();
} else {
"local"
}
.to_string()
});
Ok(match backend.as_str() {
#[cfg(feature = "local_backend")]
"local" => {
GenericConnection::Local(super::local::Connection::connect(url)?)
},
#[cfg(feature = "reqwest_backend")]
"reqwest" => {
GenericConnection::Reqwest(super::reqwest::Connection::connect_from_url(&url::Url::parse(&url)?)?)
},
#[cfg(feature = "workers_backend")]
"workers" => {
anyhow::bail!("Connecting from workers API may need access to worker::RouteContext. Please call libsql_client::workers::Connection::connect_from_ctx() directly")
},
_ => anyhow::bail!("Unknown backend: {backend}. Make sure your backend exists and is enabled with its feature flag"),
})
}
pub(crate) fn statements_to_string(
stmts: impl IntoIterator<Item = impl Into<Statement>>,
) -> (String, usize) {
let mut body = "{\"statements\": [".to_string();
let mut stmts_count = 0;
for stmt in stmts {
body += &format!("{},", stmt.into());
stmts_count += 1;
}
if stmts_count > 0 {
body.pop();
}
body += "]}";
(body, stmts_count)
}
pub(crate) fn json_to_query_result(
response_json: serde_json::Value,
stmts_count: usize,
) -> anyhow::Result<Vec<QueryResult>> {
match response_json {
serde_json::Value::Array(results) => {
if results.len() != stmts_count {
Err(anyhow::anyhow!(
"Response array did not contain expected {stmts_count} results"
))
} else {
let mut query_results: Vec<QueryResult> = Vec::with_capacity(stmts_count);
for (idx, result) in results.into_iter().enumerate() {
query_results
.push(parse_query_result(result, idx).map_err(|e| anyhow::anyhow!("{e}"))?);
}
Ok(query_results)
}
}
e => Err(anyhow::anyhow!("Error: {}", e)),
}
}