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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
use std::future::Future;
use std::sync::Arc;
use bytes::BytesMut;
use edgedb_protocol::common::CompilationOptions;
use edgedb_protocol::common::{Capabilities, Cardinality, IoFormat};
use edgedb_protocol::model::Json;
use edgedb_protocol::query_arg::{Encoder, QueryArgs};
use edgedb_protocol::QueryResult;
use tokio::sync::oneshot;
use tokio::time::sleep;
use crate::errors::ClientError;
use crate::errors::{Error, ErrorKind, SHOULD_RETRY};
use crate::errors::{NoDataError, NoResultExpected, ProtocolEncodingError};
use crate::raw::{Options, Pool, PoolConnection, PoolState};
/// Transaction object passed to the closure via
/// [`Client::transaction()`](crate::Client::transaction) method
///
/// The Transaction object must be dropped by the end of the closure execution.
///
/// All database queries in transaction should be executed using methods on
/// this object instead of using original [`Client`](crate::Client) instance.
#[derive(Debug)]
pub struct Transaction {
iteration: u32,
state: Arc<PoolState>,
inner: Option<Inner>,
}
#[derive(Debug)]
pub struct TransactionResult {
conn: PoolConnection,
started: bool,
}
#[derive(Debug)]
pub struct Inner {
started: bool,
conn: PoolConnection,
return_conn: oneshot::Sender<TransactionResult>,
}
impl Drop for Transaction {
fn drop(&mut self) {
self.inner.take().map(
|Inner {
started,
conn,
return_conn,
}| { return_conn.send(TransactionResult { started, conn }).ok() },
);
}
}
pub(crate) async fn transaction<T, B, F>(
pool: &Pool,
options: &Options,
mut body: B,
) -> Result<T, Error>
where
B: FnMut(Transaction) -> F,
F: Future<Output = Result<T, Error>>,
{
let mut iteration = 0;
'transaction: loop {
let conn = pool.acquire().await?;
let (tx, mut rx) = oneshot::channel();
let tran = Transaction {
iteration,
state: options.state.clone(),
inner: Some(Inner {
started: false,
conn,
return_conn: tx,
}),
};
let result = body(tran).await;
let TransactionResult { mut conn, started } = rx.try_recv().expect(
"Transaction object must \
be dropped by the time transaction body finishes.",
);
match result {
Ok(val) => {
log::debug!("Comitting transaction");
if started {
conn.statement("COMMIT", &options.state).await?;
}
return Ok(val);
}
Err(outer) => {
log::debug!("Rolling back transaction on error");
if started {
conn.statement("ROLLBACK", &options.state).await?;
}
let some_retry = outer.chain().find_map(|e| {
e.downcast_ref::<Error>().and_then(|e| {
if e.has_tag(SHOULD_RETRY) {
Some(e)
} else {
None
}
})
});
if some_retry.is_none() {
return Err(outer);
} else {
let e = some_retry.unwrap();
let rule = options.retry.get_rule(e);
if iteration >= rule.attempts {
return Err(outer);
} else {
log::info!("Retrying transaction on {:#}", e);
iteration += 1;
sleep((rule.backoff)(iteration)).await;
continue 'transaction;
}
}
}
}
}
}
impl Transaction {
/// Zero-based iteration (attempt) number for the current transaction
///
/// First attempt gets `iteration = 0`, second attempt `iteration = 1`,
/// etc.
pub fn iteration(&self) -> u32 {
self.iteration
}
async fn ensure_started(&mut self) -> anyhow::Result<(), Error> {
if let Some(inner) = &mut self.inner {
if !inner.started {
inner
.conn
.statement("START TRANSACTION", &self.state)
.await?;
inner.started = true;
}
return Ok(());
}
Err(ClientError::with_message("using transaction after drop"))
}
fn inner(&mut self) -> &mut Inner {
self.inner
.as_mut()
.expect("transaction object is not dropped")
}
/// Execute a query and return a collection of results.
///
/// You will usually have to specify the return type for the query:
///
/// ```rust,ignore
/// let greeting = pool.query::<String, _>("SELECT 'hello'", &());
/// // or
/// let greeting: Vec<String> = pool.query("SELECT 'hello'", &());
/// ```
///
/// This method can be used with both static arguments, like a tuple of
/// scalars, and with dynamic arguments [`edgedb_protocol::value::Value`].
/// Similarly, dynamically typed results are also supported.
pub async fn query<R, A>(&mut self, query: &str, arguments: &A) -> Result<Vec<R>, Error>
where
A: QueryArgs,
R: QueryResult,
{
self.ensure_started().await?;
let flags = CompilationOptions {
implicit_limit: None,
implicit_typenames: false,
implicit_typeids: false,
explicit_objectids: true,
allow_capabilities: Capabilities::MODIFICATIONS,
io_format: IoFormat::Binary,
expected_cardinality: Cardinality::Many,
};
let state = self.state.clone(); // TODO: optimize, by careful borrow
let conn = &mut self.inner().conn;
let desc = conn.parse(&flags, query, &state).await?;
let inp_desc = desc.input().map_err(ProtocolEncodingError::with_source)?;
let mut arg_buf = BytesMut::with_capacity(8);
arguments.encode(&mut Encoder::new(
&inp_desc.as_query_arg_context(),
&mut arg_buf,
))?;
let data = conn
.execute(&flags, query, &state, &desc, &arg_buf.freeze())
.await?;
let out_desc = desc.output().map_err(ProtocolEncodingError::with_source)?;
match out_desc.root_pos() {
Some(root_pos) => {
let ctx = out_desc.as_queryable_context();
let mut state = R::prepare(&ctx, root_pos)?;
let rows = data
.into_iter()
.flat_map(|chunk| chunk.data)
.map(|chunk| R::decode(&mut state, &chunk))
.collect::<Result<_, _>>()?;
Ok(rows)
}
None => Err(NoResultExpected::build()),
}
}
/// Execute a query and return a single result
///
/// You will usually have to specify the return type for the query:
///
/// ```rust,ignore
/// let greeting = pool.query_single::<String, _>("SELECT 'hello'", &());
/// // or
/// let greeting: Option<String> = pool.query_single(
/// "SELECT 'hello'",
/// &()
/// );
/// ```
///
/// This method can be used with both static arguments, like a tuple of
/// scalars, and with dynamic arguments [`edgedb_protocol::value::Value`].
/// Similarly, dynamically typed results are also supported.
pub async fn query_single<R, A>(
&mut self,
query: &str,
arguments: &A,
) -> Result<Option<R>, Error>
where
A: QueryArgs,
R: QueryResult,
{
self.ensure_started().await?;
let flags = CompilationOptions {
implicit_limit: None,
implicit_typenames: false,
implicit_typeids: false,
explicit_objectids: true,
allow_capabilities: Capabilities::MODIFICATIONS,
io_format: IoFormat::Binary,
expected_cardinality: Cardinality::AtMostOne,
};
let state = self.state.clone(); // TODO optimize using careful borrow
let conn = &mut self.inner().conn;
let desc = conn.parse(&flags, query, &state).await?;
let inp_desc = desc.input().map_err(ProtocolEncodingError::with_source)?;
let mut arg_buf = BytesMut::with_capacity(8);
arguments.encode(&mut Encoder::new(
&inp_desc.as_query_arg_context(),
&mut arg_buf,
))?;
let data = conn
.execute(&flags, query, &state, &desc, &arg_buf.freeze())
.await?;
let out_desc = desc.output().map_err(ProtocolEncodingError::with_source)?;
match out_desc.root_pos() {
Some(root_pos) => {
let ctx = out_desc.as_queryable_context();
let mut state = R::prepare(&ctx, root_pos)?;
let bytes = data
.into_iter()
.next()
.and_then(|chunk| chunk.data.into_iter().next());
if let Some(bytes) = bytes {
Ok(Some(R::decode(&mut state, &bytes)?))
} else {
Ok(None)
}
}
None => Err(NoResultExpected::build()),
}
}
/// Execute a query and return a single result
///
/// The query must return exactly one element. If the query returns more
/// than one element, a
/// [`ResultCardinalityMismatchError`][crate::errors::ResultCardinalityMismatchError]
/// is raised. If the query returns an empty set, a
/// [`NoDataError`][crate::errors::NoDataError] is raised.
///
/// You will usually have to specify the return type for the query:
///
/// ```rust,ignore
/// let greeting = pool.query_required_single::<String, _>(
/// "SELECT 'hello'",
/// &(),
/// );
/// // or
/// let greeting: String = pool.query_required_single(
/// "SELECT 'hello'",
/// &(),
/// );
/// ```
///
/// This method can be used with both static arguments, like a tuple of
/// scalars, and with dynamic arguments [`edgedb_protocol::value::Value`].
/// Similarly, dynamically typed results are also supported.
pub async fn query_required_single<R, A>(
&mut self,
query: &str,
arguments: &A,
) -> Result<R, Error>
where
A: QueryArgs,
R: QueryResult,
{
self.query_single(query, arguments)
.await?
.ok_or_else(|| NoDataError::with_message("query row returned zero results"))
}
/// Execute a query and return the result as JSON.
pub async fn query_json(
&mut self,
query: &str,
arguments: &impl QueryArgs,
) -> Result<Json, Error> {
self.ensure_started().await?;
let flags = CompilationOptions {
implicit_limit: None,
implicit_typenames: false,
implicit_typeids: false,
explicit_objectids: true,
allow_capabilities: Capabilities::MODIFICATIONS,
io_format: IoFormat::Json,
expected_cardinality: Cardinality::Many,
};
let state = self.state.clone(); // TODO optimize using careful borrow
let conn = &mut self.inner().conn;
let desc = conn.parse(&flags, query, &state).await?;
let inp_desc = desc.input().map_err(ProtocolEncodingError::with_source)?;
let mut arg_buf = BytesMut::with_capacity(8);
arguments.encode(&mut Encoder::new(
&inp_desc.as_query_arg_context(),
&mut arg_buf,
))?;
let data = conn
.execute(&flags, query, &state, &desc, &arg_buf.freeze())
.await?;
let out_desc = desc.output().map_err(ProtocolEncodingError::with_source)?;
match out_desc.root_pos() {
Some(root_pos) => {
let ctx = out_desc.as_queryable_context();
// JSON objects are returned as strings :(
let mut state = String::prepare(&ctx, root_pos)?;
let bytes = data
.into_iter()
.next()
.and_then(|chunk| chunk.data.into_iter().next());
if let Some(bytes) = bytes {
// we trust database to produce valid json
let s = String::decode(&mut state, &bytes)?;
Ok(Json::new_unchecked(s))
} else {
Err(NoDataError::with_message("query row returned zero results"))
}
}
None => Err(NoResultExpected::build()),
}
}
/// Execute a query and return a single result as JSON.
///
/// The query must return exactly one element. If the query returns more
/// than one element, a
/// [`ResultCardinalityMismatchError`][crate::errors::ResultCardinalityMismatchError]
/// is raised.
pub async fn query_single_json(
&mut self,
query: &str,
arguments: &impl QueryArgs,
) -> Result<Option<Json>, Error> {
self.ensure_started().await?;
let flags = CompilationOptions {
implicit_limit: None,
implicit_typenames: false,
implicit_typeids: false,
explicit_objectids: true,
allow_capabilities: Capabilities::MODIFICATIONS,
io_format: IoFormat::Json,
expected_cardinality: Cardinality::AtMostOne,
};
let state = self.state.clone(); // TODO optimize using careful borrow
let conn = &mut self.inner().conn;
let desc = conn.parse(&flags, query, &state).await?;
let inp_desc = desc.input().map_err(ProtocolEncodingError::with_source)?;
let mut arg_buf = BytesMut::with_capacity(8);
arguments.encode(&mut Encoder::new(
&inp_desc.as_query_arg_context(),
&mut arg_buf,
))?;
let data = conn
.execute(&flags, query, &state, &desc, &arg_buf.freeze())
.await?;
let out_desc = desc.output().map_err(ProtocolEncodingError::with_source)?;
match out_desc.root_pos() {
Some(root_pos) => {
let ctx = out_desc.as_queryable_context();
// JSON objects are returned as strings :(
let mut state = String::prepare(&ctx, root_pos)?;
let bytes = data
.into_iter()
.next()
.and_then(|chunk| chunk.data.into_iter().next());
if let Some(bytes) = bytes {
// we trust database to produce valid json
let s = String::decode(&mut state, &bytes)?;
Ok(Some(Json::new_unchecked(s)))
} else {
Ok(None)
}
}
None => Err(NoResultExpected::build()),
}
}
/// Execute a query and return a single result as JSON.
///
/// The query must return exactly one element. If the query returns more
/// than one element, a
/// [`ResultCardinalityMismatchError`][crate::errors::ResultCardinalityMismatchError]
/// is raised. If the query returns an empty set, a
/// [`NoDataError`][crate::errors::NoDataError] is raised.
pub async fn query_required_single_json(
&mut self,
query: &str,
arguments: &impl QueryArgs,
) -> Result<Json, Error> {
self.query_single_json(query, arguments)
.await?
.ok_or_else(|| NoDataError::with_message("query row returned zero results"))
}
/// Execute a query and don't expect result
///
/// This method can be used with both static arguments, like a tuple of
/// scalars, and with dynamic arguments [`edgedb_protocol::value::Value`].
/// Similarly, dynamically typed results are also supported.
pub async fn execute<A>(&mut self, query: &str, arguments: &A) -> Result<(), Error>
where
A: QueryArgs,
{
self.ensure_started().await?;
let flags = CompilationOptions {
implicit_limit: None,
implicit_typenames: false,
implicit_typeids: false,
explicit_objectids: true,
allow_capabilities: Capabilities::MODIFICATIONS,
io_format: IoFormat::Binary,
expected_cardinality: Cardinality::Many,
};
let state = self.state.clone(); // TODO: optimize, by careful borrow
let conn = &mut self.inner().conn;
let desc = conn.parse(&flags, query, &state).await?;
let inp_desc = desc.input().map_err(ProtocolEncodingError::with_source)?;
let mut arg_buf = BytesMut::with_capacity(8);
arguments.encode(&mut Encoder::new(
&inp_desc.as_query_arg_context(),
&mut arg_buf,
))?;
conn.execute(&flags, query, &state, &desc, &arg_buf.freeze())
.await?;
Ok(())
}
}