use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::future::{poll_fn, Future};
use std::net::Shutdown;
use std::ops::Deref;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
use crate::config::Config;
use crate::connect::{self, ReadBuf, Startup, Stream};
use crate::error::{DbError, Error, ErrorKind};
use crate::protocol::{self, parse_backend, Backend, MAX_PARAMS};
use crate::row::{Column, ResultSet, Row, RowsBuilder};
use crate::types::{ToSql, Type};
pub struct Client {
conn: Rc<Conn>,
}
pub(crate) struct Statement {
sql: Rc<str>,
name: Box<str>,
params: Vec<Type>,
columns: Rc<[Column]>,
conn: Option<Weak<Conn>>,
closed: Cell<bool>,
writes: Cell<bool>,
}
impl Drop for Statement {
fn drop(&mut self) {
let Some(conn) = self.conn.as_ref().and_then(Weak::upgrade) else {
return;
};
if !self.closed.get() {
if let Ok(mut st) = conn.state.try_borrow_mut() {
if st.broken.is_none() {
let _ = protocol::close_statement(&mut st.out, &self.name);
st.batch = None;
}
}
}
}
}
#[cold]
#[inline(never)]
fn abandoned() -> Error {
Error::new(
ErrorKind::Db,
"a statement of this transaction was given up before its answer came (its future was \
dropped, by a timeout say), and it may have run, so the transaction cannot be \
committed; this statement was not sent. Drop the transaction (which rolls it back) and \
run it again from the start",
)
}
const LEFT_OPEN: &str = "a statement sent through the pool's shared methods (Pool::batch_execute) \
left a transaction open on a connection other tasks share, so the connection was closed and \
the transaction rolled back, with every statement sent on it since BEGIN, this one included. \
Run transactions on a connection of the task's own: pool.get().await?.transaction()";
const RESET: &str = "SET SESSION AUTHORIZATION DEFAULT; RESET ALL; CLOSE ALL; UNLISTEN *; \
SELECT pg_advisory_unlock_all(); DISCARD TEMP; DISCARD SEQUENCES";
const NAME_PREFIX: &str = "__giong_";
struct Conn {
weak: Weak<Conn>,
stream: Stream,
state: RefCell<State>,
head_since: Cell<Option<giong::time::Instant>>,
config: Config,
key: Option<(i32, i32)>,
shared: Cell<bool>,
idle_wakers: RefCell<Vec<Waker>>,
requests: Cell<u64>,
lease: RefCell<Option<Arc<Lease>>>,
retire: Cell<bool>,
user_prepared: Cell<bool>,
tx: Cell<Tx>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Tx {
None,
Open,
Abandoned,
}
struct State {
out: Vec<u8>,
writer: Option<Waker>,
queue: VecDeque<Rc<Slot>>,
broken: Option<Error>,
closing: bool,
status: u8,
cache: HashMap<Rc<str>, Entry>,
clock: u64,
next_name: u64,
server_params: Vec<(String, String)>,
batch: Option<OpenBatch>,
extra: usize,
read_only_prepared: bool,
held: Vec<Rc<Slot>>,
batch_failed: bool,
}
struct OpenBatch {
start: usize,
members: usize,
}
const BATCH_MAX: usize = 16;
const SYNC_LEN: usize = 5;
const READ_ONLY: &str =
"SELECT set_config('transaction_read_only', 'on', true), set_config('lock_timeout', '50ms', true)";
const READ_ONLY_NAME: &str = "__giong_read_only";
fn read_only_guard(out: &mut Vec<u8>, prepared: bool) {
let parsed = if prepared {
Ok(())
} else {
protocol::parse(out, READ_ONLY_NAME, READ_ONLY)
};
let encoded = parsed
.and_then(|()| {
protocol::bind(
out,
READ_ONLY_NAME,
0,
|_, _| unreachable!("no parameters"),
[].into_iter(),
)
})
.and_then(|()| protocol::execute(out));
debug_assert!(encoded.is_ok(), "a constant statement encodes");
}
enum Entry {
Ready { stmt: Rc<Statement>, used: u64 },
Preparing(Rc<Slot>),
}
struct Slot {
kind: Kind,
shared: bool,
close_on_error: bool,
in_tx: Option<Weak<Conn>>,
batch: Cell<Role>,
inner: RefCell<SlotInner>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Role {
Alone,
Member,
Guard,
End,
}
enum Kind {
Prepare {
sql: Rc<str>,
name: Box<str>,
cached: bool,
},
Execute {
stmt: Rc<Statement>,
},
Simple,
}
#[derive(Default)]
struct SlotInner {
wakers: Vec<Waker>,
abandoned: bool,
delivered: bool,
error: Option<Error>,
params: Option<Vec<Type>>,
columns: Option<Vec<Column>>,
rows: RowsBuilder,
tag: Option<String>,
bound: bool,
status: u8,
retry: bool,
alone: bool,
outcome: Option<Result<Response, Error>>,
}
enum Response {
Statement(Rc<Statement>),
Rows(ResultSet, Option<String>),
Done(Option<String>),
}
impl Slot {
fn new(kind: Kind, shared: bool, close_on_error: bool, in_tx: Option<Weak<Conn>>) -> Rc<Self> {
Rc::new(Slot {
kind,
shared,
close_on_error,
in_tx,
batch: Cell::new(Role::Alone),
inner: RefCell::default(),
})
}
}
struct Wait {
slot: Rc<Slot>,
}
impl Future for Wait {
type Output = Result<Response, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut inner = self.slot.inner.borrow_mut();
let shared = matches!(self.slot.kind, Kind::Prepare { .. });
match &inner.outcome {
Some(Ok(Response::Statement(stmt))) if shared => {
return Poll::Ready(Ok(Response::Statement(stmt.clone())))
}
Some(Err(e)) if shared => return Poll::Ready(Err(e.clone())),
Some(_) => {
inner.delivered = true;
return Poll::Ready(inner.outcome.take().expect("checked"));
}
None => {}
}
if !inner.wakers.iter().any(|w| w.will_wake(cx.waker())) {
inner.wakers.push(cx.waker().clone());
}
Poll::Pending
}
}
impl Drop for Wait {
fn drop(&mut self) {
if matches!(self.slot.kind, Kind::Prepare { .. }) {
return;
}
let known = {
let mut inner = self.slot.inner.borrow_mut();
inner.abandoned = true;
inner.rows = RowsBuilder::default();
inner.delivered || inner.outcome.is_some()
};
if !known && self.slot.in_tx.is_some() {
abandon_tx(&self.slot);
}
}
}
#[cold]
#[inline(never)]
fn abandon_tx(slot: &Slot) {
if let Some(conn) = slot.in_tx.as_ref().and_then(Weak::upgrade) {
if conn.tx.get() == Tx::Open {
conn.tx.set(Tx::Abandoned);
}
}
}
fn is_stale(db: &DbError) -> bool {
match db.code() {
"26000" => true,
"0A000" => {
db.routine() == Some("RevalidateCachedQuery")
|| db.message().contains("cached plan must not change")
}
_ => false,
}
}
fn rows_affected(tag: Option<&str>) -> u64 {
tag.and_then(|t| t.rsplit(' ').next())
.and_then(|n| n.parse().ok())
.unwrap_or(0)
}
impl Client {
pub async fn connect(config: &Config) -> Result<Client, Error> {
let startup = connect::connect(config).await?;
Ok(Self::start(startup, config.clone()))
}
pub(crate) fn start(startup: Startup, config: Config) -> Client {
let Startup {
stream,
buf,
params,
key,
status,
} = startup;
let conn = Rc::new_cyclic(|weak| Conn {
weak: weak.clone(),
head_since: Cell::new(None),
stream,
config,
key,
shared: Cell::new(false),
idle_wakers: RefCell::new(Vec::new()),
requests: Cell::new(0),
lease: RefCell::new(None),
retire: Cell::new(false),
user_prepared: Cell::new(false),
tx: Cell::new(Tx::None),
state: RefCell::new(State {
out: Vec::new(),
writer: None,
queue: VecDeque::new(),
extra: 0,
read_only_prepared: false,
held: Vec::new(),
batch_failed: false,
broken: None,
closing: false,
status,
cache: HashMap::new(),
clock: 0,
next_name: 0,
server_params: params,
batch: None,
}),
});
giong::spawn(read_loop(conn.clone(), buf));
giong::spawn(write_loop(conn.clone()));
Client { conn }
}
pub async fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error> {
let (set, _) = self.run(sql, params, false).await?;
Ok(set.into_rows())
}
pub(crate) async fn query_shared(
&self,
sql: &str,
params: &[&dyn ToSql],
batch: bool,
) -> Result<Vec<Row>, Error> {
let (set, _) = self.run(sql, params, batch).await?;
Ok(set.into_rows())
}
pub async fn query_one(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row, Error> {
one_row(self.query(sql, params).await?)
}
pub async fn query_opt(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Option<Row>, Error> {
at_most_one_row(self.query(sql, params).await?)
}
}
pub(crate) fn one_row(mut rows: Vec<Row>) -> Result<Row, Error> {
match rows.len() {
1 => Ok(rows.pop().expect("one row")),
n => Err(Error::new(
ErrorKind::RowCount,
format!(
"the statement returned {n} rows where exactly one was expected; use \
query_opt for zero or one, or query for any number"
),
)),
}
}
pub(crate) fn at_most_one_row(mut rows: Vec<Row>) -> Result<Option<Row>, Error> {
match rows.len() {
0 | 1 => Ok(rows.pop()),
n => Err(Error::new(
ErrorKind::RowCount,
format!(
"the statement returned {n} rows where at most one was expected; add a \
LIMIT, or use query"
),
)),
}
}
impl Client {
pub async fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<u64, Error> {
let (_, tag) = self.run(sql, params, false).await?;
Ok(rows_affected(tag.as_deref()))
}
pub async fn batch_execute(&self, sql: &str) -> Result<(), Error> {
let slot = self
.conn
.enqueue(Kind::Simple, |out| protocol::query(out, sql))?;
Wait { slot }.await.map(|_| ())
}
pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
let tx = Transaction {
client: self,
done: false,
};
tx.client.conn.tx.set(Tx::Open);
tx.client.batch_execute("BEGIN").await?;
Ok(tx)
}
pub fn cancel_token(&self) -> CancelToken {
CancelToken {
config: self.conn.config.without_password(),
key: self.conn.key,
lease: self.conn.lease.borrow().clone(),
}
}
pub fn parameter(&self, name: &str) -> Option<String> {
let st = self.conn.state.borrow();
st.server_params
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.clone())
}
pub fn is_closed(&self) -> bool {
self.conn.state.borrow().broken.is_some()
}
pub fn in_flight(&self) -> usize {
let st = self.conn.state.borrow();
st.queue.len() - st.extra + st.held.len()
}
pub(crate) fn waiting_for(&self, now: giong::time::Instant) -> std::time::Duration {
self.conn
.head_since
.get()
.map_or(std::time::Duration::ZERO, |t| {
now.saturating_duration_since(t)
})
}
pub(crate) fn in_transaction(&self) -> bool {
self.conn.state.borrow().status != b'I'
}
pub(crate) fn set_shared(&self, shared: bool) {
self.conn.shared.set(shared);
}
pub(crate) fn wake_when_idle(&self, waker: &Waker) {
let mut wakers = self.conn.idle_wakers.borrow_mut();
if !wakers.iter().any(|w| w.will_wake(waker)) {
wakers.push(waker.clone());
}
}
pub(crate) fn requests(&self) -> u64 {
self.conn.requests.get()
}
pub(crate) fn begin_lease(&self) {
*self.conn.lease.borrow_mut() = Some(Arc::new(Lease::default()));
}
pub(crate) fn end_lease(&self) -> bool {
self.conn
.lease
.borrow_mut()
.take()
.is_some_and(|lease| lease.end())
}
pub(crate) fn should_retire(&self) -> bool {
self.conn.retire.get()
}
pub(crate) fn reset_session(&self) {
let deallocate = self.conn.user_prepared.replace(false);
let sql = if deallocate {
let mut st = self.conn.state.borrow_mut();
st.cache.clear();
st.read_only_prepared = false;
format!("{RESET}; DEALLOCATE ALL")
} else {
RESET.to_owned()
};
if let Ok(slot) = self
.conn
.enqueue_with(Kind::Simple, true, |out| protocol::query(out, &sql))
{
slot.inner.borrow_mut().abandoned = true;
}
}
pub(crate) fn send_and_forget(&self, sql: &str) {
if let Ok(slot) = self
.conn
.enqueue(Kind::Simple, |out| protocol::query(out, sql))
{
slot.inner.borrow_mut().abandoned = true;
}
}
async fn run(
&self,
sql: &str,
params: &[&dyn ToSql],
batch: bool,
) -> Result<(ResultSet, Option<String>), Error> {
if params.len() > MAX_PARAMS {
return Err(Error::conversion(format!(
"{} parameters were given; a statement can have at most {MAX_PARAMS}",
params.len()
)));
}
let mut retried = false;
let mut alone = !batch;
loop {
let slot = self.send(sql, params, !alone).await?;
let result = Wait { slot: slot.clone() }.await;
if result.is_err() {
let (skipped, stale) = {
let inner = slot.inner.borrow();
(inner.alone, inner.retry)
};
if skipped && !alone {
alone = true;
continue;
}
if stale && !retried {
retried = true;
continue;
}
}
return match result? {
Response::Rows(set, tag) => Ok((set, tag)),
_ => unreachable!("an execute slot ends with rows"),
};
}
}
async fn send(&self, sql: &str, params: &[&dyn ToSql], batch: bool) -> Result<Rc<Slot>, Error> {
let stmt = self.conn.statement(sql).await?;
if stmt.params.len() != params.len() {
return Err(Error::conversion(format!(
"the statement has {} parameters but {} values were given",
stmt.params.len(),
params.len()
)));
}
let cached = stmt.conn.is_none();
let encode = |out: &mut Vec<u8>| {
protocol::bind(
out,
&stmt.name,
params.len(),
|i, out| {
params[i].to_sql(stmt.params[i], out).map_err(|e| {
e.context(&format!("parameter ${} ({})", i + 1, stmt.params[i]))
})
},
stmt.columns.iter().map(|c| c.ty().binary_result()),
)?;
protocol::execute(out)
};
let kind = Kind::Execute { stmt: stmt.clone() };
let slot = if batch
&& cached
&& !stmt.writes.get()
&& self.conn.shared.get()
&& self.conn.tx.get() == Tx::None
{
self.conn.enqueue_batched(kind, encode)?
} else {
self.conn.enqueue(kind, |out| {
encode(out)?;
protocol::sync(out);
Ok(())
})?
};
if !cached {
let close = self.conn.enqueue(Kind::Simple, |out| {
protocol::close_statement(out, &stmt.name)?;
protocol::sync(out);
Ok(())
});
if let Ok(close) = close {
close.inner.borrow_mut().abandoned = true;
stmt.closed.set(true);
}
}
Ok(slot)
}
}
impl Drop for Client {
fn drop(&mut self) {
let mut st = self.conn.state.borrow_mut();
st.closing = true;
if st.broken.is_none() {
protocol::terminate(&mut st.out);
st.batch = None;
}
if let Some(w) = st.writer.take() {
w.wake();
}
}
}
impl std::fmt::Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("server", &self.conn.config.target())
.field("in_flight", &self.in_flight())
.field("closed", &self.is_closed())
.finish()
}
}
impl Conn {
fn enqueue(
&self,
kind: Kind,
encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
) -> Result<Rc<Slot>, Error> {
self.enqueue_with(kind, false, encode)
}
#[cold]
#[inline(never)]
fn in_tx(&self) -> Result<Weak<Conn>, Error> {
match self.tx.get() {
Tx::Abandoned => Err(abandoned()),
_ => Ok(self.weak.clone()),
}
}
fn enqueue_with(
&self,
kind: Kind,
close_on_error: bool,
encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
) -> Result<Rc<Slot>, Error> {
let mut st = self.state.borrow_mut();
if let Some(e) = &st.broken {
return Err(e.clone());
}
let in_tx = if self.tx.get() == Tx::None {
None
} else {
Some(self.in_tx()?)
};
st.batch = None;
let start = st.out.len();
if let Err(e) = encode(&mut st.out) {
st.out.truncate(start);
return Err(e);
}
let slot = Slot::new(kind, self.shared.get(), close_on_error, in_tx);
self.requests.set(self.requests.get() + 1);
if st.queue.is_empty() {
self.head_since.set(Some(giong::time::Instant::now()));
}
st.queue.push_back(slot.clone());
if let Some(w) = st.writer.take() {
w.wake();
}
Ok(slot)
}
#[inline(never)]
fn enqueue_batched(
&self,
kind: Kind,
encode: impl FnOnce(&mut Vec<u8>) -> Result<(), Error>,
) -> Result<Rc<Slot>, Error> {
let mut st = self.state.borrow_mut();
if let Some(e) = &st.broken {
return Err(e.clone());
}
let joins = st.batch.as_ref().is_some_and(|b| b.members < BATCH_MAX);
if !joins {
let start = st.out.len();
if let Err(e) = encode(&mut st.out) {
st.out.truncate(start);
return Err(e);
}
protocol::sync(&mut st.out);
st.batch = Some(OpenBatch { start, members: 1 });
return Ok(self.queue_slot(&mut st, Slot::new(kind, true, false, None)));
}
let mut messages = Vec::new();
encode(&mut messages)?;
let sync_at = st.out.len() - SYNC_LEN;
st.out.truncate(sync_at);
let b = st.batch.as_mut().expect("joins");
if b.members == 1 {
let start = b.start;
let mut guard = Vec::new();
read_only_guard(&mut guard, st.read_only_prepared);
st.read_only_prepared = true;
st.out.splice(start..start, guard);
let first = st.queue.pop_back().expect("the batch's first statement");
first.batch.set(Role::Member);
let guard = Slot::new(Kind::Simple, true, false, None);
guard.batch.set(Role::Guard);
st.extra += 2; guard.inner.borrow_mut().abandoned = true;
st.queue.push_back(guard);
st.queue.push_back(first);
} else {
let end = st.queue.pop_back().expect("the batch's end");
debug_assert_eq!(end.batch.get(), Role::End);
}
st.batch.as_mut().expect("joins").members += 1;
st.out.extend_from_slice(&messages);
protocol::sync(&mut st.out);
let slot = Slot::new(kind, true, false, None);
slot.batch.set(Role::Member);
st.queue.push_back(slot.clone());
let end = Slot::new(Kind::Simple, true, false, None);
end.batch.set(Role::End);
end.inner.borrow_mut().abandoned = true;
self.queue_slot(&mut st, end);
Ok(slot)
}
fn queue_slot(&self, st: &mut State, slot: Rc<Slot>) -> Rc<Slot> {
self.requests.set(self.requests.get() + 1);
if st.queue.is_empty() {
self.head_since.set(Some(giong::time::Instant::now()));
}
st.queue.push_back(slot.clone());
if let Some(w) = st.writer.take() {
w.wake();
}
slot
}
fn finish_member(&self, slot: &Rc<Slot>) {
slot.inner.borrow_mut().status = b'I';
let mut st = self.state.borrow_mut();
st.queue.pop_front();
if slot.batch.get() == Role::Guard {
st.extra -= 1;
} else {
st.held.push(slot.clone());
}
self.head_since
.set((!st.queue.is_empty()).then(giong::time::Instant::now));
}
async fn statement(&self, sql: &str) -> Result<Rc<Statement>, Error> {
let mut again = true;
loop {
let pending = {
let mut st = self.state.borrow_mut();
st.clock += 1;
let now = st.clock;
match st.cache.get_mut(sql) {
Some(Entry::Ready { stmt, used }) => {
*used = now;
return Ok(stmt.clone());
}
Some(Entry::Preparing(slot)) => Some(slot.clone()),
None => None,
}
};
let Some(slot) = pending else {
return self.prepare(sql).await;
};
match (Wait { slot }).await {
Ok(Response::Statement(stmt)) => return Ok(stmt),
Ok(_) => unreachable!("a prepare slot ends with a statement"),
Err(e) if again && e.server_code() == Some("42P05") => again = false,
Err(e) => return Err(e),
}
}
}
async fn prepare(&self, sql: &str) -> Result<Rc<Statement>, Error> {
match self.prepare_once(sql).await {
Err(e) if e.server_code() == Some("42P05") => self.prepare_once(sql).await,
result => result,
}
}
async fn prepare_once(&self, sql: &str) -> Result<Rc<Statement>, Error> {
let cached = self.config.statement_cache > 0;
let (name, key) = {
let mut st = self.state.borrow_mut();
st.next_name += 1;
(
format!("{NAME_PREFIX}{}", st.next_name),
Rc::<str>::from(sql),
)
};
let slot = self.enqueue(
Kind::Prepare {
sql: key.clone(),
name: name.as_str().into(),
cached,
},
|out| {
protocol::parse(out, &name, sql)?;
protocol::describe_statement(out, &name)?;
protocol::sync(out);
Ok(())
},
)?;
if cached {
self.state
.borrow_mut()
.cache
.insert(key, Entry::Preparing(slot.clone()));
}
match (Wait { slot }).await? {
Response::Statement(stmt) => Ok(stmt),
_ => unreachable!("a prepare slot ends with a statement"),
}
}
fn fail(&self, err: Error) {
let slots = {
let mut st = self.state.borrow_mut();
if st.broken.is_none() {
st.broken = Some(err.clone());
}
st.cache.clear();
st.out.clear();
self.head_since.set(None);
if let Some(w) = st.writer.take() {
w.wake();
}
st.extra = 0;
st.read_only_prepared = false;
st.batch_failed = false;
let mut slots = std::mem::take(&mut st.held);
slots.extend(std::mem::take(&mut st.queue));
slots
};
for slot in slots {
let mut inner = slot.inner.borrow_mut();
let e = inner.error.take().unwrap_or_else(|| err.clone());
inner.outcome = Some(Err(e));
for w in inner.wakers.drain(..) {
w.wake();
}
}
self.wake_idle();
self.stream.shutdown(Shutdown::Both);
}
fn wake_idle(&self) {
let wakers = std::mem::take(&mut *self.idle_wakers.borrow_mut());
for w in wakers {
w.wake();
}
}
fn process(&self, buf: &mut ReadBuf) -> Result<(), Error> {
let limit = self.config.max_result_size.max(1 << 20);
while let Some((tag, len)) = buf.peek()? {
if len > limit {
match tag {
b'D' => self.front()?.inner.borrow_mut().rows.set_overflow(),
b'N' | b'A' | b'd' => {}
b'E' => {
let slot = self.front()?;
let mut inner = slot.inner.borrow_mut();
if inner.error.is_none() {
inner.error = Some(Error::new(
ErrorKind::TooLarge,
format!(
"the server's error for this statement was a {len}-byte \
message, more than max_result_size allows, so it was \
thrown away; raise Config::max_result_size to read it"
),
));
}
}
_ => {
return Err(Error::new(
ErrorKind::Protocol,
format!(
"the server sent a {:?} message of {len} bytes, more than \
max_result_size allows, so the connection was closed; raise \
Config::max_result_size if the server's messages are this large",
tag as char
),
))
}
}
buf.skip(len);
continue;
}
let Some(body) = buf.body(len) else {
return Ok(());
};
self.handle(tag, buf.bytes(body))?;
buf.consume(len);
}
Ok(())
}
fn front(&self) -> Result<Rc<Slot>, Error> {
self.state.borrow().queue.front().cloned().ok_or_else(|| {
Error::protocol("the server sent a reply to a request that was never made")
})
}
fn handle(&self, tag: u8, body: &[u8]) -> Result<(), Error> {
let msg = parse_backend(tag, body)?;
match msg {
Backend::NoticeResponse | Backend::NotificationResponse => return Ok(()),
Backend::ParameterStatus { name, value } => {
if name == "client_encoding" && !value.eq_ignore_ascii_case("UTF8") {
return Err(Error::closed(format!(
"the session's client_encoding was changed to {value}; giong-postgres \
reads and writes UTF-8 only, so the connection was closed"
)));
}
let mut st = self.state.borrow_mut();
match st.server_params.iter_mut().find(|(n, _)| n == name) {
Some(entry) => entry.1 = value.to_owned(),
None => st.server_params.push((name.to_owned(), value.to_owned())),
}
return Ok(());
}
Backend::ErrorResponse(fields) if self.state.borrow().queue.is_empty() => {
let db = DbError::parse(fields)?;
return Err(Error::with_db(
ErrorKind::Closed,
"the server closed the connection",
db,
));
}
_ => {}
}
let slot = loop {
let slot = self.front()?;
if slot.batch.get() != Role::Alone
&& matches!(
msg,
Backend::CommandComplete(_)
| Backend::ErrorResponse(_)
| Backend::ReadyForQuery(_)
)
{
if self.handle_batched(slot, &msg)? {
continue;
}
return Ok(());
}
break slot;
};
let mut inner = slot.inner.borrow_mut();
match msg {
Backend::BindComplete => inner.bound = true,
Backend::ParseComplete
| Backend::CloseComplete
| Backend::NoData
| Backend::PortalSuspended
| Backend::EmptyQueryResponse => {}
Backend::ParameterDescription(types) => inner.params = Some(types),
Backend::RowDescription(fields) => {
if matches!(slot.kind, Kind::Prepare { .. }) {
inner.columns = Some(
fields
.iter()
.map(|f| Column::new(f.name, Type::from_oid(f.type_oid)))
.collect(),
);
}
}
Backend::DataRow(body) => match &slot.kind {
Kind::Execute { stmt } if !inner.abandoned && inner.error.is_none() => {
let limit = self.config.max_result_size;
inner.rows.push(body, stmt.columns.len(), limit)?;
}
_ => {}
},
Backend::CommandComplete(tag) => {
if tag == "PREPARE" {
self.user_prepared.set(true);
}
inner.tag = Some(tag.to_owned());
}
Backend::ErrorResponse(fields) => {
if inner.error.is_none() {
inner.error = Some(self.db_error(fields, true)?);
}
}
Backend::CopyOutResponse | Backend::CopyData | Backend::CopyDone => {
if inner.error.is_none() {
inner.error = Some(Error::conversion(
"COPY ... TO STDOUT is not supported by giong-postgres yet; the output \
was thrown away",
));
}
}
Backend::CopyInResponse | Backend::CopyBothResponse => {
return Err(Error::closed(
"the statement started COPY FROM STDIN or replication, which giong-postgres \
does not support yet; the connection was closed",
));
}
Backend::ReadyForQuery(status) => {
let left_open = slot.shared && status != b'I';
if left_open {
inner.error = Some(Error::closed(LEFT_OPEN));
}
let reset_failed = match &inner.error {
Some(e) if slot.close_on_error => Some(Error::closed(format!(
"resetting the session of a connection that went back to the pool \
failed, so it was closed rather than reused: {e}"
))),
_ => None,
};
inner.status = status;
drop(inner);
let idle = {
let mut st = self.state.borrow_mut();
st.status = status;
st.queue.pop_front();
self.head_since
.set((!st.queue.is_empty()).then(giong::time::Instant::now));
st.queue.is_empty()
};
self.complete(&slot);
if left_open {
return Err(Error::closed(LEFT_OPEN));
}
if let Some(e) = reset_failed {
return Err(e);
}
if idle {
self.wake_idle();
}
}
other => {
return Err(Error::protocol(format!(
"the server sent an unexpected {:?} message ({other:?})",
tag as char
)))
}
}
Ok(())
}
fn db_error(&self, fields: &[u8], may_retire: bool) -> Result<Error, Error> {
let db = DbError::parse(fields)?;
if may_retire && db.code() == "25006" && self.on_standby() {
self.retire.set(true);
}
let note = (db.code() == "57014" && db.message().contains("statement timeout")).then(
|| match self.config.statement_timeout {
Some(limit) => format!(
"the statement ran longer than the statement timeout ({limit:?}; \
Config::statement_timeout)"
),
None => "the statement ran longer than the server's statement_timeout".to_owned(),
},
);
Ok(Error::from_db(db, note))
}
#[cold]
#[inline(never)]
fn handle_batched(&self, slot: Rc<Slot>, msg: &Backend<'_>) -> Result<bool, Error> {
let mut inner = slot.inner.borrow_mut();
match *msg {
Backend::CommandComplete(command) => {
inner.tag = Some(command.to_owned());
}
Backend::ErrorResponse(fields) => {
let error = self.db_error(fields, false)?;
self.state.borrow_mut().batch_failed = true;
match slot.batch.get() {
Role::End => return Ok(false),
Role::Guard if error.server_code() == Some("26000") => {
self.state.borrow_mut().read_only_prepared = false;
}
_ => {}
}
if matches!(error.server_code(), Some("55P03" | "40P01" | "40001"))
&& slot.batch.get() == Role::Member
{
if let Kind::Execute { .. } = &slot.kind {
inner.alone = true;
}
}
if error.server_code() == Some("25006") {
if let Kind::Execute { stmt } = &slot.kind {
stmt.writes.set(true);
inner.alone = true;
}
}
inner.error = Some(error);
}
Backend::ReadyForQuery(status) if slot.batch.get() == Role::End => {
inner.status = status;
drop(inner);
let (idle, held, failed) = {
let mut st = self.state.borrow_mut();
st.status = status;
st.queue.pop_front();
st.extra -= 1;
self.head_since
.set((!st.queue.is_empty()).then(giong::time::Instant::now));
let failed = std::mem::take(&mut st.batch_failed);
(st.queue.is_empty(), std::mem::take(&mut st.held), failed)
};
for member in &held {
if failed {
let mut inner = member.inner.borrow_mut();
if inner.error.is_none() {
inner.error = Some(Error::new(
ErrorKind::Closed,
"another statement of this one's batch failed, so the batch \
was rolled back",
));
inner.alone = matches!(member.kind, Kind::Execute { .. });
}
}
self.complete(member);
}
self.complete(&slot);
if idle {
self.wake_idle();
}
return Ok(false);
}
Backend::ReadyForQuery(_) => {
inner.error = Some(Error::new(
ErrorKind::Closed,
"a statement before this one in its batch failed, so the server skipped it",
));
inner.alone = matches!(slot.kind, Kind::Execute { .. });
drop(inner);
self.finish_member(&slot);
return Ok(true);
}
_ => unreachable!("only these three come here"),
}
drop(inner);
self.finish_member(&slot);
Ok(false)
}
fn complete(&self, slot: &Rc<Slot>) {
let mut inner = slot.inner.borrow_mut();
let error = inner.error.take();
let outcome = match &slot.kind {
Kind::Prepare { sql, name, cached } => {
let result = match error {
Some(e) => Err(e),
None => match inner.params.take() {
Some(params) => Ok(Rc::new(Statement {
sql: sql.clone(),
name: name.clone(),
params,
columns: inner.columns.take().unwrap_or_default().into(),
conn: (!*cached).then(|| self.weak.clone()),
closed: Cell::new(false),
writes: Cell::new(false),
})),
None => Err(Error::protocol("the server did not describe the statement")),
},
};
if *cached {
self.settle_cache(sql, slot, &result);
}
result.map(Response::Statement)
}
Kind::Execute { stmt } => match error {
Some(e) => {
let stale = self.forget_if_stale(stmt, &e);
inner.retry = stale && !inner.bound && inner.status == b'I';
Err(e)
}
None if inner.rows.overflow => Err(Error::new(
ErrorKind::TooLarge,
format!(
"the result is larger than max_result_size ({} bytes); add a LIMIT or \
select fewer columns, or raise Config::max_result_size",
self.config.max_result_size
),
)),
None => {
let rows = std::mem::take(&mut inner.rows);
Ok(Response::Rows(
rows.finish(stmt.columns.clone()),
inner.tag.take(),
))
}
},
Kind::Simple => match error {
Some(e) => Err(e),
None => Ok(Response::Done(inner.tag.take())),
},
};
inner.outcome = Some(outcome);
for w in inner.wakers.drain(..) {
w.wake();
}
}
fn forget_if_stale(&self, stmt: &Statement, e: &Error) -> bool {
if !e.db().is_some_and(is_stale) {
return false;
}
let mut st = self.state.borrow_mut();
if matches!(st.cache.get(&stmt.sql), Some(Entry::Ready { stmt: s, .. }) if s.name == stmt.name)
{
st.cache.remove(&stmt.sql);
}
true
}
fn on_standby(&self) -> bool {
let st = self.state.borrow();
st.server_params
.iter()
.find(|(n, _)| n == "in_hot_standby")
.map_or(true, |(_, v)| v != "off")
}
fn settle_cache(&self, sql: &Rc<str>, slot: &Rc<Slot>, result: &Result<Rc<Statement>, Error>) {
let mut st = self.state.borrow_mut();
let ours = matches!(st.cache.get(sql), Some(Entry::Preparing(s)) if Rc::ptr_eq(s, slot));
if !ours {
return;
}
let Ok(stmt) = result else {
st.cache.remove(sql);
return;
};
st.clock += 1;
let used = st.clock;
st.cache.insert(
sql.clone(),
Entry::Ready {
stmt: stmt.clone(),
used,
},
);
while st.cache.len() > self.config.statement_cache {
let victim = st
.cache
.iter()
.filter_map(|(k, e)| match e {
Entry::Ready { stmt, used } if Rc::strong_count(stmt) == 1 => {
Some((*used, k.clone()))
}
_ => None,
})
.min();
let Some((_, key)) = victim else { break };
if let Some(Entry::Ready { stmt, .. }) = st.cache.remove(&key) {
let _ = protocol::close_statement(&mut st.out, &stmt.name);
st.batch = None;
}
}
}
}
async fn read_loop(conn: Rc<Conn>, mut buf: ReadBuf) {
let err = loop {
if let Err(e) = conn.process(&mut buf) {
break e;
}
match conn.stream.read_into(&mut buf).await {
Ok(0) => {
let closing = conn.state.borrow().closing;
break Error::closed(if closing {
"the connection was closed"
} else {
"the server closed the connection"
});
}
Ok(_) => {}
Err(e) => break Error::io(ErrorKind::Closed, "reading from the server failed", e),
}
};
conn.fail(err);
}
async fn write_loop(conn: Rc<Conn>) {
let mut spare = Vec::new();
loop {
let next = poll_fn(|cx| {
let mut st = conn.state.borrow_mut();
if st.broken.is_some() {
return Poll::Ready(None);
}
if !st.out.is_empty() {
st.batch = None;
return Poll::Ready(Some(std::mem::replace(
&mut st.out,
std::mem::take(&mut spare),
)));
}
if st.closing {
return Poll::Ready(None);
}
st.writer = Some(cx.waker().clone());
Poll::Pending
})
.await;
let Some(data) = next else { break };
let (written, mut data) = conn.stream.write_all(data).await;
if let Err(e) = written {
conn.fail(Error::io(
ErrorKind::Closed,
"writing to the server failed",
e,
));
return;
}
data.clear();
spare = data;
}
if conn.state.borrow().closing {
conn.stream.shutdown(Shutdown::Write);
}
}
pub struct Transaction<'a> {
client: &'a mut Client,
done: bool,
}
impl Transaction<'_> {
pub async fn commit(mut self) -> Result<(), Error> {
if self.client.conn.tx.get() == Tx::Abandoned {
return Err(abandoned());
}
self.end();
let slot = self
.client
.conn
.enqueue(Kind::Simple, |out| protocol::query(out, "COMMIT"))?;
match (Wait { slot }).await? {
Response::Done(Some(tag)) if tag == "ROLLBACK" => Err(Error::with_sqlstate(
"25P02",
"the transaction was rolled back instead of committed, because a statement in \
it failed earlier",
)),
_ => Ok(()),
}
}
pub async fn rollback(mut self) -> Result<(), Error> {
self.end();
self.client.batch_execute("ROLLBACK").await
}
fn end(&mut self) {
self.done = true;
self.client.conn.tx.set(Tx::None);
}
}
impl Deref for Transaction<'_> {
type Target = Client;
fn deref(&self) -> &Client {
self.client
}
}
impl Drop for Transaction<'_> {
fn drop(&mut self) {
if !self.done {
self.end();
self.client.send_and_forget("ROLLBACK");
}
}
}
impl std::fmt::Debug for Transaction<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Transaction")
.field("client", &self.client)
.finish()
}
}
#[derive(Clone)]
pub struct CancelToken {
config: Config,
key: Option<(i32, i32)>,
lease: Option<Arc<Lease>>,
}
#[derive(Default)]
pub(crate) struct Lease(AtomicU32);
impl Lease {
const ENDED: u32 = 1 << 31;
fn start_cancel(&self) -> bool {
let mut v = self.0.load(Ordering::Acquire);
while v & Self::ENDED == 0 {
match self
.0
.compare_exchange_weak(v, v + 1, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => return true,
Err(now) => v = now,
}
}
false
}
fn finish_cancel(&self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
fn is_ended(&self) -> bool {
self.0.load(Ordering::Acquire) & Self::ENDED != 0
}
fn end(&self) -> bool {
self.0.fetch_or(Self::ENDED, Ordering::AcqRel) & !Self::ENDED != 0
}
}
impl CancelToken {
pub async fn cancel(&self) -> Result<(), Error> {
let gone = || {
Error::closed(
"the connection this cancel token was taken from has gone back to its pool, \
where other tasks use it, so nothing was sent; take a new token from the next \
connection",
)
};
if self.lease.as_ref().is_some_and(|lease| lease.is_ended()) {
return Err(gone());
}
let key = self.key.ok_or_else(|| {
Error::new(
ErrorKind::Connect,
"the server gave this connection no cancel key (a connection pooler may be in \
between), so it cannot be cancelled",
)
})?;
let Some(lease) = &self.lease else {
return connect::cancel(&self.config, key).await;
};
if !lease.start_cancel() {
return Err(gone());
}
let sent = connect::cancel(&self.config, key).await;
lease.finish_cancel();
sent
}
}
impl std::fmt::Debug for CancelToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CancelToken")
.field("server", &self.config.target())
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::{is_stale, rows_affected};
use crate::error::DbError;
fn db_error(fields: &[(u8, &str)]) -> DbError {
let mut body = Vec::new();
for (field, value) in fields {
body.push(*field);
body.extend_from_slice(value.as_bytes());
body.push(0);
}
body.push(0);
DbError::parse(&body).unwrap()
}
#[test]
fn a_stale_plan_is_recognised_in_any_language() {
let german = db_error(&[
(b'S', "FEHLER"),
(b'V', "ERROR"),
(b'C', "0A000"),
(b'M', "gecachter Plan darf den Ergebnistyp nicht ändern"),
(b'R', "RevalidateCachedQuery"),
]);
assert!(is_stale(&german));
assert_eq!(german.severity(), "ERROR");
let english = db_error(&[
(b'C', "0A000"),
(b'M', "cached plan must not change result type"),
]);
assert!(is_stale(&english));
let other = db_error(&[
(b'C', "0A000"),
(b'M', "nicht unterstützt"),
(b'R', "transformSelectStmt"),
]);
assert!(!is_stale(&other));
assert!(is_stale(&db_error(&[(b'C', "26000"), (b'M', "x")])));
}
#[test]
fn command_tags_give_row_counts() {
assert_eq!(rows_affected(Some("INSERT 0 5")), 5);
assert_eq!(rows_affected(Some("UPDATE 3")), 3);
assert_eq!(rows_affected(Some("SELECT 12")), 12);
assert_eq!(rows_affected(Some("CREATE TABLE")), 0);
assert_eq!(rows_affected(None), 0);
}
}