smarm-pg 0.1.0: the Postgres client from the urus + smarm Conduit server
Extracted from rust-urus-markk116 (db/wire.rs, db/types.rs). Changes on the way: - Config (was DbConfig) takes startup options; plan_cache_mode/jit are now the app's choice - PgConn::query for single statements - bool parameters and results; FromSql for time::OffsetDateTime (feature time) replaces the app-specific Timestamp - a parameter count mismatch is refused before sending and leaves the connection usable - lib denies unwrap/expect, as smarm does Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011iFkM6QYfk9aJxpog3uuTj
This commit is contained in:
+562
@@ -0,0 +1,562 @@
|
||||
//! One connection: blocking from the calling actor's point of view, parking on smarm's fd
|
||||
//! readiness when the socket would block.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, Read as _, Write as _};
|
||||
use std::net::TcpStream;
|
||||
use std::os::fd::{AsRawFd, RawFd};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use postgres_protocol::authentication::sasl::{ChannelBinding, ScramSha256};
|
||||
use postgres_protocol::message::frontend;
|
||||
|
||||
use crate::error::{PgError, PgResult};
|
||||
use crate::rows::{be_i32, Rows};
|
||||
use crate::stmt::{oid, Param, Step, Stmt};
|
||||
use crate::types::ToParam;
|
||||
|
||||
/// Where to connect, as whom, and the session settings to start with.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub user: String,
|
||||
pub password: String,
|
||||
pub dbname: String,
|
||||
/// Run-time parameters sent in the startup message (`plan_cache_mode`, `jit`, …): in force
|
||||
/// for the whole session, at no extra round trip.
|
||||
pub options: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// `postgres://user:pass@host:port/db` (or `postgresql://`). The query string is ignored
|
||||
/// and nothing is percent-decoded.
|
||||
pub fn parse(url: &str) -> Option<Config> {
|
||||
let rest = url.strip_prefix("postgres://").or_else(|| url.strip_prefix("postgresql://"))?;
|
||||
let (auth, hostdb) = rest.rsplit_once('@')?;
|
||||
let (user, password) = auth.split_once(':').unwrap_or((auth, ""));
|
||||
let (hostport, db) = hostdb.split_once('/')?;
|
||||
let db = db.split('?').next()?;
|
||||
let (host, port) = match hostport.rsplit_once(':') {
|
||||
Some((h, p)) => (h, p.parse().ok()?),
|
||||
None => (hostport, 5432),
|
||||
};
|
||||
Some(Config {
|
||||
host: host.to_string(),
|
||||
port,
|
||||
user: user.to_string(),
|
||||
password: password.to_string(),
|
||||
dbname: db.to_string(),
|
||||
options: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Add a session setting for the startup message.
|
||||
pub fn option(mut self, name: &str, value: &str) -> Config {
|
||||
self.options.push((name.to_string(), value.to_string()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PgConn {
|
||||
_sock: TcpStream,
|
||||
fd: RawFd,
|
||||
rbuf: Vec<u8>,
|
||||
rpos: usize,
|
||||
wbuf: BytesMut,
|
||||
/// Server-side name for each statement this connection has seen, by [`Stmt::key`], and
|
||||
/// whether the server has confirmed preparing it (ParseComplete).
|
||||
statements: HashMap<usize, (String, bool)>,
|
||||
broken: bool,
|
||||
}
|
||||
|
||||
impl PgConn {
|
||||
/// Connects and authenticates (trust, cleartext, MD5 or SCRAM-SHA-256 without channel
|
||||
/// binding). Startup runs on a blocking socket (it happens a handful of times per process);
|
||||
/// the socket goes non-blocking afterwards.
|
||||
pub fn connect(cfg: &Config) -> PgResult<PgConn> {
|
||||
let mut sock = TcpStream::connect((cfg.host.as_str(), cfg.port))?;
|
||||
sock.set_nodelay(true)?;
|
||||
let mut buf = BytesMut::new();
|
||||
let params = [("user", cfg.user.as_str()), ("database", cfg.dbname.as_str()), ("client_encoding", "UTF8")]
|
||||
.into_iter()
|
||||
.chain(cfg.options.iter().map(|(k, v)| (k.as_str(), v.as_str())));
|
||||
frontend::startup_message(params, &mut buf)?;
|
||||
sock.write_all(&buf)?;
|
||||
buf.clear();
|
||||
|
||||
let mut scram: Option<ScramSha256> = None;
|
||||
loop {
|
||||
let (tag, body) = read_msg_blocking(&mut sock)?;
|
||||
match tag {
|
||||
b'R' => {
|
||||
if body.len() < 4 {
|
||||
return Err(PgError::Protocol("short authentication message"));
|
||||
}
|
||||
match be_i32(&body[0..4]) {
|
||||
0 => {}
|
||||
3 => frontend::password_message(cfg.password.as_bytes(), &mut buf)?,
|
||||
5 => {
|
||||
let salt = body.get(4..8).ok_or(PgError::Protocol("short MD5 salt"))?;
|
||||
let pw = postgres_protocol::authentication::md5_hash(
|
||||
cfg.user.as_bytes(),
|
||||
cfg.password.as_bytes(),
|
||||
[salt[0], salt[1], salt[2], salt[3]],
|
||||
);
|
||||
frontend::password_message(pw.as_bytes(), &mut buf)?;
|
||||
}
|
||||
10 => {
|
||||
let s = ScramSha256::new(cfg.password.as_bytes(), ChannelBinding::unsupported());
|
||||
frontend::sasl_initial_response("SCRAM-SHA-256", s.message(), &mut buf)?;
|
||||
scram = Some(s);
|
||||
}
|
||||
11 => {
|
||||
let s = scram.as_mut().ok_or(PgError::Protocol("sasl continue without start"))?;
|
||||
s.update(&body[4..])?;
|
||||
frontend::sasl_response(s.message(), &mut buf)?;
|
||||
}
|
||||
12 => {
|
||||
let s = scram.as_mut().ok_or(PgError::Protocol("sasl final without start"))?;
|
||||
s.finish(&body[4..])?;
|
||||
}
|
||||
_ => return Err(PgError::Protocol("unsupported auth method")),
|
||||
}
|
||||
if !buf.is_empty() {
|
||||
sock.write_all(&buf)?;
|
||||
buf.clear();
|
||||
}
|
||||
}
|
||||
b'E' => return Err(parse_error(&body)),
|
||||
b'Z' => break,
|
||||
_ => {} // ParameterStatus, BackendKeyData, NoticeResponse
|
||||
}
|
||||
}
|
||||
sock.set_nonblocking(true)?;
|
||||
let fd = sock.as_raw_fd();
|
||||
Ok(PgConn {
|
||||
_sock: sock,
|
||||
fd,
|
||||
rbuf: Vec::with_capacity(16 * 1024),
|
||||
rpos: 0,
|
||||
wbuf: BytesMut::with_capacity(4096),
|
||||
statements: HashMap::new(),
|
||||
broken: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// False once an IO or protocol error has left the connection unusable.
|
||||
pub fn is_healthy(&self) -> bool {
|
||||
!self.broken
|
||||
}
|
||||
|
||||
/// Run one statement.
|
||||
pub fn query(&mut self, stmt: &'static Stmt, params: &[&dyn ToParam]) -> PgResult<Rows> {
|
||||
let step = Step { stmt, params: params.iter().map(|p| p.to_param()).collect() };
|
||||
let mut results = self.pipe(std::slice::from_ref(&step))?;
|
||||
results.pop().ok_or(PgError::Protocol("result count mismatch"))
|
||||
}
|
||||
|
||||
/// [`pipeline`](Self::pipeline), failing on the first statement error (the batch is
|
||||
/// all-or-nothing anyway).
|
||||
pub fn pipe(&mut self, steps: &[Step]) -> PgResult<Vec<Rows>> {
|
||||
self.pipeline(steps)?.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Run several statements behind one Sync: one round trip, one implicit transaction (an
|
||||
/// error in any of them rolls all of them back). Per-statement results; statements after a
|
||||
/// failed one are reported as skipped.
|
||||
pub fn pipeline(&mut self, steps: &[Step]) -> PgResult<Vec<PgResult<Rows>>> {
|
||||
if self.broken {
|
||||
return Err(PgError::Protocol("connection broken"));
|
||||
}
|
||||
if steps.iter().any(|step| step.stmt.types.len() != step.params.len()) {
|
||||
// Caught before anything is sent, so the connection stays usable.
|
||||
return Err(PgError::Protocol("parameter count differs from the statement's types"));
|
||||
}
|
||||
let r = self.pipeline_inner(steps);
|
||||
if let Err(e) = &r {
|
||||
if e.fatal() {
|
||||
self.broken = true;
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn pipeline_inner(&mut self, steps: &[Step]) -> PgResult<Vec<PgResult<Rows>>> {
|
||||
self.wbuf.clear();
|
||||
for step in steps {
|
||||
self.encode(step.stmt, &step.params);
|
||||
}
|
||||
frontend::sync(&mut self.wbuf);
|
||||
self.flush()?;
|
||||
|
||||
let mut results: Vec<PgResult<Rows>> = Vec::with_capacity(steps.len());
|
||||
let mut cur = Rows::default();
|
||||
let mut idx = 0usize;
|
||||
loop {
|
||||
let (tag, start, end) = self.next_msg()?;
|
||||
match tag {
|
||||
b'1' => {
|
||||
if let Some(entry) = steps.get(idx).and_then(|step| self.statements.get_mut(&step.stmt.key())) {
|
||||
entry.1 = true;
|
||||
}
|
||||
}
|
||||
b'2' | b'n' | b'I' | b's' => {}
|
||||
b'D' => {
|
||||
let body = &self.rbuf[start..end];
|
||||
let n = u16::from_be_bytes([body[0], body[1]]) as usize;
|
||||
cur.ncols = n;
|
||||
let mut p = 2;
|
||||
for _ in 0..n {
|
||||
let l = be_i32(&body[p..p + 4]);
|
||||
p += 4;
|
||||
let off = cur.data.len() as u32;
|
||||
if l > 0 {
|
||||
cur.data.extend_from_slice(&body[p..p + l as usize]);
|
||||
p += l as usize;
|
||||
}
|
||||
cur.cols.push((off, l));
|
||||
}
|
||||
}
|
||||
b'C' => {
|
||||
let body = &self.rbuf[start..end];
|
||||
let tagstr = std::str::from_utf8(&body[..body.len().saturating_sub(1)]).unwrap_or("");
|
||||
cur.affected = tagstr.rsplit(' ').next().and_then(|n| n.parse().ok()).unwrap_or(0);
|
||||
results.push(Ok(std::mem::take(&mut cur)));
|
||||
idx += 1;
|
||||
}
|
||||
b'E' => {
|
||||
results.push(Err(parse_error(&self.rbuf[start..end])));
|
||||
idx += 1;
|
||||
}
|
||||
b'Z' => break,
|
||||
b'N' | b'S' | b'A' => {}
|
||||
_ => return Err(PgError::Protocol("unexpected message")),
|
||||
}
|
||||
}
|
||||
// After an error the server skips the rest of the batch: report those as errors too.
|
||||
while results.len() < steps.len() {
|
||||
results.push(Err(PgError::Protocol("skipped after earlier error")));
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Parse (until the server has confirmed it once), Bind, Execute.
|
||||
fn encode(&mut self, st: &'static Stmt, params: &[Param]) {
|
||||
let next = self.statements.len();
|
||||
let (name, prepared) = self.statements.entry(st.key()).or_insert_with(|| (format!("s{next}"), false));
|
||||
let w = &mut self.wbuf;
|
||||
if !*prepared {
|
||||
let _ = frontend::parse(name, st.sql, st.types.iter().copied(), w);
|
||||
}
|
||||
// Bind: portal "", statement, 1 format code (binary for all), params, 1 result format (binary).
|
||||
w.extend_from_slice(b"B");
|
||||
let len_at = w.len();
|
||||
w.extend_from_slice(&[0; 4]);
|
||||
w.extend_from_slice(b"\0");
|
||||
w.extend_from_slice(name.as_bytes());
|
||||
w.extend_from_slice(b"\0");
|
||||
w.extend_from_slice(&1i16.to_be_bytes());
|
||||
w.extend_from_slice(&1i16.to_be_bytes());
|
||||
w.extend_from_slice(&(params.len() as i16).to_be_bytes());
|
||||
for p in params {
|
||||
match p {
|
||||
Param::Null => w.extend_from_slice(&(-1i32).to_be_bytes()),
|
||||
Param::Bool(v) => {
|
||||
w.extend_from_slice(&1i32.to_be_bytes());
|
||||
w.extend_from_slice(&[u8::from(*v)]);
|
||||
}
|
||||
Param::I8(v) => {
|
||||
w.extend_from_slice(&8i32.to_be_bytes());
|
||||
w.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
Param::Text(s) => {
|
||||
w.extend_from_slice(&(s.len() as i32).to_be_bytes());
|
||||
w.extend_from_slice(s.as_bytes());
|
||||
}
|
||||
Param::TextArr(items) => {
|
||||
let start = w.len();
|
||||
w.extend_from_slice(&[0; 4]);
|
||||
w.extend_from_slice(&1i32.to_be_bytes()); // ndim
|
||||
w.extend_from_slice(&0i32.to_be_bytes()); // has nulls
|
||||
w.extend_from_slice(&oid::TEXT.to_be_bytes());
|
||||
w.extend_from_slice(&(items.len() as i32).to_be_bytes());
|
||||
w.extend_from_slice(&1i32.to_be_bytes()); // lower bound
|
||||
for it in items {
|
||||
w.extend_from_slice(&(it.len() as i32).to_be_bytes());
|
||||
w.extend_from_slice(it.as_bytes());
|
||||
}
|
||||
let l = (w.len() - start - 4) as i32;
|
||||
w[start..start + 4].copy_from_slice(&l.to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
w.extend_from_slice(&1i16.to_be_bytes());
|
||||
w.extend_from_slice(&1i16.to_be_bytes());
|
||||
let l = (w.len() - len_at) as i32;
|
||||
w[len_at..len_at + 4].copy_from_slice(&l.to_be_bytes());
|
||||
let _ = frontend::execute("", 0, w);
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
let mut off = 0;
|
||||
while off < self.wbuf.len() {
|
||||
// SAFETY: the pointer and length describe the unwritten tail of wbuf.
|
||||
let n = unsafe { libc::write(self.fd, self.wbuf[off..].as_ptr().cast(), self.wbuf.len() - off) };
|
||||
if n >= 0 {
|
||||
off += n as usize;
|
||||
continue;
|
||||
}
|
||||
let e = io::Error::last_os_error();
|
||||
match e.kind() {
|
||||
io::ErrorKind::WouldBlock => smarm::wait_writable(self.fd)?,
|
||||
io::ErrorKind::Interrupted => {}
|
||||
_ => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Next backend message: (tag, body start, body end) into rbuf. Reads optimistically and
|
||||
/// only parks on epoll when the socket really has nothing.
|
||||
fn next_msg(&mut self) -> PgResult<(u8, usize, usize)> {
|
||||
loop {
|
||||
let avail = self.rbuf.len() - self.rpos;
|
||||
if avail >= 5 {
|
||||
let len = be_i32(&self.rbuf[self.rpos + 1..self.rpos + 5]) as usize;
|
||||
if avail > len {
|
||||
let tag = self.rbuf[self.rpos];
|
||||
let start = self.rpos + 5;
|
||||
let end = self.rpos + 1 + len;
|
||||
self.rpos = end;
|
||||
return Ok((tag, start, end));
|
||||
}
|
||||
}
|
||||
if self.rpos > 0 {
|
||||
self.rbuf.drain(..self.rpos);
|
||||
self.rpos = 0;
|
||||
}
|
||||
let have = self.rbuf.len();
|
||||
if self.rbuf.capacity() - have < 8192 {
|
||||
self.rbuf.reserve(16 * 1024);
|
||||
}
|
||||
let cap = self.rbuf.capacity();
|
||||
// SAFETY: reads into rbuf's spare capacity; set_len only covers the bytes read.
|
||||
let n = unsafe { libc::read(self.fd, self.rbuf.as_mut_ptr().add(have).cast(), cap - have) };
|
||||
if n > 0 {
|
||||
unsafe { self.rbuf.set_len(have + n as usize) };
|
||||
continue;
|
||||
}
|
||||
if n == 0 {
|
||||
return Err(PgError::Io(io::ErrorKind::UnexpectedEof.into()));
|
||||
}
|
||||
let e = io::Error::last_os_error();
|
||||
match e.kind() {
|
||||
io::ErrorKind::WouldBlock => smarm::wait_readable(self.fd)?,
|
||||
io::ErrorKind::Interrupted => {}
|
||||
_ => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_msg_blocking(sock: &mut TcpStream) -> io::Result<(u8, Vec<u8>)> {
|
||||
let mut head = [0u8; 5];
|
||||
sock.read_exact(&mut head)?;
|
||||
let len = be_i32(&head[1..5]) as usize;
|
||||
let mut body = vec![0u8; len.saturating_sub(4)];
|
||||
sock.read_exact(&mut body)?;
|
||||
Ok((head[0], body))
|
||||
}
|
||||
|
||||
fn parse_error(body: &[u8]) -> PgError {
|
||||
let mut code = String::new();
|
||||
let mut message = String::new();
|
||||
let mut p = 0;
|
||||
while p < body.len() && body[p] != 0 {
|
||||
let field = body[p];
|
||||
let end = body[p + 1..].iter().position(|&b| b == 0).map_or(body.len(), |i| p + 1 + i);
|
||||
let val = String::from_utf8_lossy(&body[p + 1..end]).into_owned();
|
||||
match field {
|
||||
b'C' => code = val,
|
||||
b'M' => message = val,
|
||||
_ => {}
|
||||
}
|
||||
p = end + 1;
|
||||
}
|
||||
PgError::Db { code, message }
|
||||
}
|
||||
|
||||
// Against a real Postgres at TEST_DATABASE_URL (skipped when unset). Only session-local temp
|
||||
// tables are created, so any database the role can connect to will do.
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::oid::{BOOL, INT8, TEXT, TEXT_ARR};
|
||||
|
||||
static SELECT_INT: Stmt = Stmt::read("SELECT $1::int8", &[INT8]);
|
||||
static ECHO: Stmt = Stmt::read("SELECT $1::bool, $2::text, $3::text[]", &[BOOL, TEXT, TEXT_ARR]);
|
||||
static DIV_ZERO: Stmt = Stmt::read("SELECT 1 / 0", &[]);
|
||||
static MAKE_TEMP: Stmt = Stmt::write("CREATE TEMP TABLE IF NOT EXISTS t (k text PRIMARY KEY)", &[]);
|
||||
static INSERT: Stmt = Stmt::write("INSERT INTO t VALUES ($1)", &[TEXT]);
|
||||
static COUNT: Stmt = Stmt::read("SELECT count(*) FROM t", &[]);
|
||||
static SHAPES: Stmt = Stmt::read(
|
||||
"SELECT NULL::text, $1::text, ARRAY['b', 'a']::text[], ARRAY[]::text[], true, \
|
||||
'2025-04-01T12:00:00.1239Z'::timestamptz",
|
||||
&[TEXT],
|
||||
);
|
||||
static SETTING: Stmt = Stmt::read("SELECT current_setting('application_name')", &[]);
|
||||
static DIE: Stmt = Stmt::read("SELECT pg_terminate_backend(pg_backend_pid())", &[]);
|
||||
|
||||
fn step(stmt: &'static Stmt, params: &[Param]) -> Step {
|
||||
Step { stmt, params: params.to_vec() }
|
||||
}
|
||||
|
||||
fn config() -> Option<Config> {
|
||||
let cfg = std::env::var("TEST_DATABASE_URL").ok().and_then(|u| Config::parse(&u));
|
||||
if cfg.is_none() {
|
||||
eprintln!("TEST_DATABASE_URL not set: skipping");
|
||||
}
|
||||
cfg
|
||||
}
|
||||
|
||||
/// Run `f` with a fresh connection inside a smarm runtime (the client parks on epoll).
|
||||
fn with_conn(f: impl FnOnce(&mut PgConn) + Send + 'static) {
|
||||
let Some(cfg) = config() else { return };
|
||||
smarm::run(move || {
|
||||
let mut c = PgConn::connect(&cfg).unwrap();
|
||||
f(&mut c);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_urls() {
|
||||
let c = Config::parse("postgresql://u:p:w@db.local:6543/app?sslmode=disable").unwrap();
|
||||
assert_eq!((c.user.as_str(), c.password.as_str()), ("u", "p:w"));
|
||||
assert_eq!((c.host.as_str(), c.port, c.dbname.as_str()), ("db.local", 6543, "app"));
|
||||
assert_eq!(Config::parse("postgres://u@h/db").unwrap().port, 5432);
|
||||
assert!(Config::parse("mysql://u@h/db").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statement_is_prepared_once_and_reused() {
|
||||
with_conn(|c| {
|
||||
for v in [7i64, 8] {
|
||||
assert_eq!(c.query(&SELECT_INT, &[&v]).unwrap().i64(0, 0), v);
|
||||
}
|
||||
assert_eq!(c.statements.len(), 1);
|
||||
assert!(c.statements[&SELECT_INT.key()].1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_round_trip() {
|
||||
with_conn(|c| {
|
||||
let tags = vec!["x".to_string(), String::new(), "ü".to_string()];
|
||||
let r = c.query(&ECHO, &[&true, &"hi", &tags]).unwrap();
|
||||
assert!(r.bool(0, 0));
|
||||
assert_eq!(r.str(0, 1), "hi");
|
||||
assert_eq!(r.text_array(0, 2).collect::<Vec<_>>(), ["x", "", "ü"]);
|
||||
let r = c.query(&ECHO, &[&false, &None::<String>, &Vec::<String>::new()]).unwrap();
|
||||
assert!(!r.bool(0, 0));
|
||||
assert_eq!(r.opt_str(0, 1), None);
|
||||
assert_eq!(r.text_array(0, 2).count(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_parameter_count_is_refused_before_sending() {
|
||||
with_conn(|c| {
|
||||
let e = c.pipe(&[step(&SELECT_INT, &[])]).err().unwrap();
|
||||
assert!(matches!(e, PgError::Protocol(_)));
|
||||
assert!(c.is_healthy());
|
||||
assert_eq!(c.query(&SELECT_INT, &[&5i64]).unwrap().i64(0, 0), 5);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_options_apply_to_the_session() {
|
||||
let Some(cfg) = config() else { return };
|
||||
let cfg = cfg.option("application_name", "smarm-pg-test");
|
||||
smarm::run(move || {
|
||||
let mut c = PgConn::connect(&cfg).unwrap();
|
||||
assert_eq!(c.query(&SETTING, &[]).unwrap().str(0, 0), "smarm-pg-test");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_mid_batch_skips_the_rest_and_leaves_the_connection_usable() {
|
||||
with_conn(|c| {
|
||||
let one = [Param::I8(1)];
|
||||
let res =
|
||||
c.pipeline(&[step(&SELECT_INT, &one), step(&DIV_ZERO, &[]), step(&SELECT_INT, &one)]).unwrap();
|
||||
assert!(res[0].is_ok());
|
||||
assert!(matches!(&res[1], Err(PgError::Db { code, .. }) if code == "22012"));
|
||||
assert!(res[2].is_err());
|
||||
assert!(c.is_healthy());
|
||||
// The statement after the error never ran, but its Parse might have: either way
|
||||
// the next use must work (a stale "prepared" flag would break it).
|
||||
assert_eq!(c.query(&SELECT_INT, &[&3i64]).unwrap().i64(0, 0), 3);
|
||||
// DIV_ZERO's Parse succeeded before it failed at execution; the rollback must not
|
||||
// have taken the prepared statement with it (26000 would mean a stale flag).
|
||||
let again = c.query(&DIV_ZERO, &[]).err().unwrap();
|
||||
assert!(matches!(&again, PgError::Db { code, .. } if code == "22012"), "{again}");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_is_one_transaction() {
|
||||
with_conn(|c| {
|
||||
c.query(&MAKE_TEMP, &[]).unwrap();
|
||||
let res = c.pipeline(&[step(&INSERT, &[Param::Text("x".into())]), step(&DIV_ZERO, &[])]).unwrap();
|
||||
assert!(res[0].is_ok() && res[1].is_err());
|
||||
assert_eq!(c.query(&COUNT, &[]).unwrap().i64(0, 0), 0, "insert rolled back");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unique_violation_is_recognised() {
|
||||
with_conn(|c| {
|
||||
c.query(&MAKE_TEMP, &[]).unwrap();
|
||||
c.query(&INSERT, &[&"dup"]).unwrap();
|
||||
let e = c.query(&INSERT, &[&"dup"]).err().unwrap();
|
||||
assert!(e.is_unique_violation());
|
||||
assert!(c.is_healthy());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_nulls_text_arrays_bools_and_timestamps() {
|
||||
with_conn(|c| {
|
||||
let r = c.query(&SHAPES, &[&"héllo \"q\""]).unwrap();
|
||||
assert_eq!(r.opt_str(0, 0), None);
|
||||
assert_eq!(r.str(0, 1), "héllo \"q\"");
|
||||
assert_eq!(r.text_array(0, 2).collect::<Vec<_>>(), ["b", "a"]);
|
||||
assert_eq!(r.text_array(0, 3).count(), 0);
|
||||
assert!(r.bool(0, 4));
|
||||
// timestamptz: µs since 2000-01-01Z
|
||||
assert_eq!(r.i64(0, 5), 796_824_000_123_900);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
#[test]
|
||||
fn decodes_timestamptz_as_offset_date_time() {
|
||||
with_conn(|c| {
|
||||
let r = c.query(&SHAPES, &[&""]).unwrap();
|
||||
let t: time::OffsetDateTime = crate::FromSql::from_sql(&r, 0, 5).unwrap();
|
||||
assert_eq!(t.unix_timestamp_nanos(), 1_743_508_800_123_900_000);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dead_backend_breaks_the_connection_for_good() {
|
||||
with_conn(|c| {
|
||||
let e = c.query(&DIE, &[]).err().unwrap();
|
||||
assert!(e.fatal(), "{e}");
|
||||
assert!(!c.is_healthy());
|
||||
assert!(c.query(&SELECT_INT, &[&1i64]).is_err());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use std::io;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PgError {
|
||||
Io(io::Error),
|
||||
/// An error the server reported (an ErrorResponse): SQLSTATE and message.
|
||||
Db { code: String, message: String },
|
||||
Protocol(&'static str),
|
||||
}
|
||||
|
||||
impl PgError {
|
||||
pub fn is_unique_violation(&self) -> bool {
|
||||
matches!(self, PgError::Db { code, .. } if code == "23505")
|
||||
}
|
||||
|
||||
/// Anything but a server-reported error leaves the connection in an unknown state.
|
||||
pub fn fatal(&self) -> bool {
|
||||
!matches!(self, PgError::Db { .. })
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for PgError {
|
||||
fn from(e: io::Error) -> Self {
|
||||
PgError::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PgError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PgError::Io(e) => write!(f, "io: {e}"),
|
||||
PgError::Db { code, message } => write!(f, "db {code}: {message}"),
|
||||
PgError::Protocol(m) => write!(f, "protocol: {m}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PgError {}
|
||||
|
||||
pub type PgResult<T> = Result<T, PgError>;
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
//! A small Postgres client for [smarm](https://git.kalsbeek.dev/Markk116/smarm) actors.
|
||||
//!
|
||||
//! Calls block the calling actor, not the scheduler thread: socket reads and writes are tried
|
||||
//! first and the actor only parks on smarm's fd readiness on `EAGAIN`. No async, no runtime of
|
||||
//! its own.
|
||||
//!
|
||||
//! - Extended protocol only. Statements are `static` [`Stmt`]s; a connection prepares each one
|
||||
//! the first time it runs it (the Parse goes out in the same write as the Bind/Execute, so a
|
||||
//! cold statement still costs one round trip) and reuses it afterwards.
|
||||
//! - Binary parameters and results.
|
||||
//! - [`PgConn::pipeline`] sends several statements behind one Sync: one round trip, one
|
||||
//! implicit transaction.
|
||||
//!
|
||||
//! One [`PgConn`] is one connection, used by one actor at a time. Pooling is left to the
|
||||
//! application: in smarm the natural shape is an actor per connection under a supervisor.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use smarm_pg::{oid, Config, PgConn, Stmt};
|
||||
//!
|
||||
//! static ADD: Stmt = Stmt::read("SELECT $1::int8 + 1", &[oid::INT8]);
|
||||
//!
|
||||
//! smarm::run(|| {
|
||||
//! let cfg = Config::parse("postgres://app:secret@127.0.0.1/app").unwrap();
|
||||
//! let mut conn = PgConn::connect(&cfg).unwrap();
|
||||
//! let rows = conn.query(&ADD, &[&41i64]).unwrap();
|
||||
//! assert_eq!(rows.first::<i64>().unwrap(), Some(42));
|
||||
//! });
|
||||
//! ```
|
||||
|
||||
mod conn;
|
||||
mod error;
|
||||
mod rows;
|
||||
mod stmt;
|
||||
mod types;
|
||||
|
||||
pub use conn::{Config, PgConn};
|
||||
pub use error::{PgError, PgResult};
|
||||
pub use rows::{Rows, TextArrayIter};
|
||||
pub use stmt::{oid, Param, Step, Stmt};
|
||||
pub use types::{FromRow, FromSql, Row, ToParam};
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
/// The result of one statement: all its DataRows in one buffer.
|
||||
#[derive(Default)]
|
||||
pub struct Rows {
|
||||
pub(crate) data: Vec<u8>,
|
||||
/// (start, len) per column, len -1 = NULL, row-major.
|
||||
pub(crate) cols: Vec<(u32, i32)>,
|
||||
pub(crate) ncols: usize,
|
||||
/// Affected-row count from CommandComplete (INSERT/UPDATE/DELETE).
|
||||
pub affected: u64,
|
||||
}
|
||||
|
||||
impl Rows {
|
||||
pub fn len(&self) -> usize {
|
||||
self.cols.len().checked_div(self.ncols).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
/// The binary value at row `r`, column `c`; `None` for NULL.
|
||||
#[inline]
|
||||
pub fn raw(&self, r: usize, c: usize) -> Option<&[u8]> {
|
||||
let (s, l) = self.cols[r * self.ncols + c];
|
||||
if l < 0 {
|
||||
None
|
||||
} else {
|
||||
Some(&self.data[s as usize..s as usize + l as usize])
|
||||
}
|
||||
}
|
||||
|
||||
/// int8 or int4; also a timestamptz's microseconds since 2000-01-01Z. 0 for NULL.
|
||||
pub fn i64(&self, r: usize, c: usize) -> i64 {
|
||||
match self.raw(r, c) {
|
||||
Some(b) if b.len() == 8 => i64::from_be_bytes(b.try_into().unwrap_or([0; 8])),
|
||||
Some(b) if b.len() == 4 => i32::from_be_bytes(b.try_into().unwrap_or([0; 4])) as i64,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bool(&self, r: usize, c: usize) -> bool {
|
||||
matches!(self.raw(r, c), Some([1]))
|
||||
}
|
||||
|
||||
/// Text; "" for NULL.
|
||||
pub fn str(&self, r: usize, c: usize) -> &str {
|
||||
self.opt_str(r, c).unwrap_or("")
|
||||
}
|
||||
|
||||
pub fn opt_str(&self, r: usize, c: usize) -> Option<&str> {
|
||||
// Postgres guarantees valid UTF-8 for text in a UTF8 database.
|
||||
self.raw(r, c).map(|b| std::str::from_utf8(b).unwrap_or(""))
|
||||
}
|
||||
|
||||
/// One-dimensional text[] (binary array format); empty for NULL.
|
||||
pub fn text_array(&self, r: usize, c: usize) -> TextArrayIter<'_> {
|
||||
let b = self.raw(r, c).unwrap_or(&[]);
|
||||
if b.len() < 12 {
|
||||
return TextArrayIter { b: &[], left: 0 };
|
||||
}
|
||||
let ndim = be_i32(&b[0..4]);
|
||||
if ndim == 0 {
|
||||
return TextArrayIter { b: &[], left: 0 };
|
||||
}
|
||||
let n = be_i32(&b[12..16]).max(0) as usize;
|
||||
TextArrayIter { b: &b[12 + 8 * ndim as usize..], left: n }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TextArrayIter<'a> {
|
||||
b: &'a [u8],
|
||||
left: usize,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for TextArrayIter<'a> {
|
||||
type Item = &'a str;
|
||||
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
if self.left == 0 || self.b.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
self.left -= 1;
|
||||
let l = be_i32(&self.b[..4]);
|
||||
if l < 0 {
|
||||
self.b = &self.b[4..];
|
||||
return Some("");
|
||||
}
|
||||
let (s, rest) = self.b[4..].split_at(l as usize);
|
||||
self.b = rest;
|
||||
Some(std::str::from_utf8(s).unwrap_or(""))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn be_i32(b: &[u8]) -> i32 {
|
||||
i32::from_be_bytes([b[0], b[1], b[2], b[3]])
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/// Type OIDs for [`Stmt`] parameter lists: the types [`Param`] can encode.
|
||||
pub mod oid {
|
||||
pub const BOOL: u32 = 16;
|
||||
pub const INT8: u32 = 20;
|
||||
pub const TEXT: u32 = 25;
|
||||
pub const TEXT_ARR: u32 = 1009;
|
||||
}
|
||||
|
||||
/// A statement the application runs. Declare each one as a `static`: a connection prepares it
|
||||
/// the first time it runs it and recognises it afterwards by its address.
|
||||
pub struct Stmt {
|
||||
pub sql: &'static str,
|
||||
/// Parameter type OIDs, one per `$n` (see [`oid`]).
|
||||
pub types: &'static [u32],
|
||||
/// Whether it changes data. The client doesn't use this itself; it is there so a pool can
|
||||
/// route writes, which wait for a WAL flush on commit, away from reads.
|
||||
pub writes: bool,
|
||||
}
|
||||
|
||||
impl Stmt {
|
||||
pub const fn read(sql: &'static str, types: &'static [u32]) -> Stmt {
|
||||
Stmt { sql, types, writes: false }
|
||||
}
|
||||
|
||||
pub const fn write(sql: &'static str, types: &'static [u32]) -> Stmt {
|
||||
Stmt { sql, types, writes: true }
|
||||
}
|
||||
|
||||
pub(crate) fn key(&'static self) -> usize {
|
||||
std::ptr::from_ref(self) as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// A statement parameter, in the binary wire format of its declared type. Owned, so a batch
|
||||
/// can be sent to the actor that holds the connection.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Param {
|
||||
Null,
|
||||
Bool(bool),
|
||||
I8(i64),
|
||||
Text(String),
|
||||
TextArr(Vec<String>),
|
||||
}
|
||||
|
||||
/// One statement and its parameters.
|
||||
pub struct Step {
|
||||
pub stmt: &'static Stmt,
|
||||
pub params: Vec<Param>,
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
//! Conversions between Rust values and statement parameters / result columns.
|
||||
|
||||
use crate::error::{PgError, PgResult};
|
||||
use crate::rows::Rows;
|
||||
use crate::stmt::Param;
|
||||
|
||||
/// A value that can be passed as a statement parameter.
|
||||
pub trait ToParam {
|
||||
fn to_param(&self) -> Param;
|
||||
}
|
||||
|
||||
impl ToParam for bool {
|
||||
fn to_param(&self) -> Param {
|
||||
Param::Bool(*self)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToParam for i64 {
|
||||
fn to_param(&self) -> Param {
|
||||
Param::I8(*self)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToParam for str {
|
||||
fn to_param(&self) -> Param {
|
||||
Param::Text(self.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToParam for String {
|
||||
fn to_param(&self) -> Param {
|
||||
Param::Text(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ToParam> ToParam for Option<T> {
|
||||
fn to_param(&self) -> Param {
|
||||
self.as_ref().map_or(Param::Null, ToParam::to_param)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToParam for [String] {
|
||||
fn to_param(&self) -> Param {
|
||||
Param::TextArr(self.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToParam for Vec<String> {
|
||||
fn to_param(&self) -> Param {
|
||||
Param::TextArr(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ToParam + ?Sized> ToParam for &T {
|
||||
fn to_param(&self) -> Param {
|
||||
(**self).to_param()
|
||||
}
|
||||
}
|
||||
|
||||
/// A value that can be read from one result column.
|
||||
pub trait FromSql: Sized {
|
||||
fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult<Self>;
|
||||
}
|
||||
|
||||
fn not_null(rows: &Rows, row: usize, col: usize) -> PgResult<()> {
|
||||
match rows.raw(row, col) {
|
||||
Some(_) => Ok(()),
|
||||
None => Err(PgError::Protocol("unexpected NULL")),
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for i64 {
|
||||
fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult<Self> {
|
||||
not_null(rows, row, col)?;
|
||||
Ok(rows.i64(row, col))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for bool {
|
||||
fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult<Self> {
|
||||
not_null(rows, row, col)?;
|
||||
Ok(rows.bool(row, col))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for String {
|
||||
fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult<Self> {
|
||||
not_null(rows, row, col)?;
|
||||
Ok(rows.str(row, col).to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for Option<String> {
|
||||
fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult<Self> {
|
||||
Ok(rows.opt_str(row, col).map(str::to_owned))
|
||||
}
|
||||
}
|
||||
|
||||
/// text[]; NULL reads as empty.
|
||||
impl FromSql for Vec<String> {
|
||||
fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult<Self> {
|
||||
Ok(rows.text_array(row, col).map(str::to_owned).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// 2000-01-01T00:00:00Z, Postgres's timestamp epoch, in Unix microseconds.
|
||||
#[cfg(feature = "time")]
|
||||
const PG_EPOCH_UNIX_MICROS: i128 = 946_684_800_000_000;
|
||||
|
||||
/// timestamptz, in UTC.
|
||||
#[cfg(feature = "time")]
|
||||
impl FromSql for time::OffsetDateTime {
|
||||
fn from_sql(rows: &Rows, row: usize, col: usize) -> PgResult<Self> {
|
||||
let pg_micros = i64::from_sql(rows, row, col)?;
|
||||
let unix_nanos = (PG_EPOCH_UNIX_MICROS + i128::from(pg_micros)) * 1000;
|
||||
time::OffsetDateTime::from_unix_timestamp_nanos(unix_nanos)
|
||||
.map_err(|_| PgError::Protocol("timestamp out of range"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the columns of one result row in order, so a [`FromRow`] impl lists its fields in the
|
||||
/// same order as the SELECT list it reads.
|
||||
pub struct Row<'a> {
|
||||
rows: &'a Rows,
|
||||
row: usize,
|
||||
col: usize,
|
||||
}
|
||||
|
||||
impl Row<'_> {
|
||||
/// The next column.
|
||||
pub fn get<T: FromSql>(&mut self) -> PgResult<T> {
|
||||
let value = T::from_sql(self.rows, self.row, self.col)?;
|
||||
self.col += 1;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// A value built from one result row.
|
||||
pub trait FromRow: Sized {
|
||||
fn from_row(row: &mut Row) -> PgResult<Self>;
|
||||
}
|
||||
|
||||
impl FromRow for i64 {
|
||||
fn from_row(row: &mut Row) -> PgResult<Self> {
|
||||
row.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRow for bool {
|
||||
fn from_row(row: &mut Row) -> PgResult<Self> {
|
||||
row.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRow for String {
|
||||
fn from_row(row: &mut Row) -> PgResult<Self> {
|
||||
row.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: FromSql, B: FromSql> FromRow for (A, B) {
|
||||
fn from_row(row: &mut Row) -> PgResult<Self> {
|
||||
Ok((row.get()?, row.get()?))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: FromSql, B: FromSql, C: FromSql> FromRow for (A, B, C) {
|
||||
fn from_row(row: &mut Row) -> PgResult<Self> {
|
||||
Ok((row.get()?, row.get()?, row.get()?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Rows {
|
||||
/// Every row, decoded.
|
||||
pub fn all<T: FromRow>(&self) -> PgResult<Vec<T>> {
|
||||
(0..self.len()).map(|row| self.decode(row)).collect()
|
||||
}
|
||||
|
||||
/// The first row, if there is one.
|
||||
pub fn first<T: FromRow>(&self) -> PgResult<Option<T>> {
|
||||
if self.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
self.decode(0).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
fn decode<T: FromRow>(&self, row: usize) -> PgResult<T> {
|
||||
T::from_row(&mut Row { rows: self, row, col: 0 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user