Skip to main content

turnloop_postgres/
lib.rs

1#![deny(unsafe_op_in_unsafe_fn)]
2#![forbid(unsafe_code)]
3//! Pull-based, bounded, sans-I/O PostgreSQL client.
4//!
5//! Feed bytes with `receive`, pull `next_event`, write `output`, then acknowledge
6//! only transmitted bytes with `consume_output`. Events borrow reusable storage.
7//! The host owns sockets, TLS, entropy, time and result materialization.
8
9#[cfg(all(target_os = "wasi", target_env = "p3"))]
10use turnloop_wasi_random as _;
11
12use bytes::BytesMut;
13pub use postgres_protocol::authentication::sasl::{ChannelBinding, ScramSha256};
14use postgres_protocol::{
15    IsNull,
16    authentication::md5_hash,
17    message::{backend::Header, frontend},
18};
19use std::{collections::VecDeque, fmt};
20pub mod pool;
21pub mod types;
22mod wire;
23use wire::Cursor;
24pub use wire::{Field, Fields, Row, ServerError};
25
26#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
27mod host_time;
28#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
29pub use host_time::Instant;
30#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
31pub use std::time::Instant;
32
33pub type Token = u64;
34pub type Result<T> = std::result::Result<T, Error>;
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Error {
37    Protocol(&'static str),
38    State(&'static str),
39    Limit,
40    Timeout,
41    Transport,
42    Cancelled,
43}
44impl fmt::Display for Error {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Self::Protocol(s) | Self::State(s) => f.write_str(s),
48            Self::Limit => f.write_str("protocol buffer limit exceeded"),
49            Self::Timeout => f.write_str("Connection terminated due to timeout"),
50            Self::Transport => f.write_str("Connection terminated unexpectedly"),
51            Self::Cancelled => f.write_str("Connection terminated"),
52        }
53    }
54}
55impl std::error::Error for Error {}
56impl From<std::io::Error> for Error {
57    fn from(_: std::io::Error) -> Self {
58        Self::Protocol("invalid PostgreSQL message")
59    }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum SslMode {
64    Disable,
65    Prefer,
66    Require,
67}
68#[derive(Clone)]
69pub struct Config {
70    pub user: String,
71    pub password: Vec<u8>,
72    pub database: String,
73    pub application_name: String,
74    pub ssl: SslMode,
75    /// Require SCRAM-SHA-256-PLUS; the host supplies tls-server-end-point data.
76    pub channel_binding_required: bool,
77    pub max_buffer: usize,
78    pub max_pending: usize,
79    pub max_scram_iterations: u32,
80    pub connect_deadline: Option<Instant>,
81}
82impl Default for Config {
83    fn default() -> Self {
84        Self {
85            user: "postgres".into(),
86            password: Vec::new(),
87            database: "postgres".into(),
88            application_name: "turnloop".into(),
89            ssl: SslMode::Disable,
90            channel_binding_required: false,
91            max_buffer: 64 * 1024 * 1024,
92            max_pending: 1024,
93            max_scram_iterations: 1_000_000,
94            connect_deadline: None,
95        }
96    }
97}
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum TransactionStatus {
100    Idle,
101    InTransaction,
102    Failed,
103}
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum Outcome {
106    Success,
107    ServerError,
108    Aborted(Error),
109}
110#[derive(Debug)]
111pub enum Event<'a> {
112    UpgradeTls,
113    /// Build upstream ScramSha256 outside the core (its constructor reads entropy).
114    ScramNeeded {
115        plus: bool,
116    },
117    Connected,
118    ParameterStatus {
119        name: &'a str,
120        value: &'a str,
121    },
122    Fields {
123        token: Token,
124        fields: Fields<'a>,
125    },
126    Row {
127        token: Token,
128        row: Row<'a>,
129    },
130    CommandComplete {
131        token: Token,
132        tag: &'a str,
133        row_count: Option<u64>,
134    },
135    Error {
136        token: Option<Token>,
137        error: ServerError<'a>,
138    },
139    Notice(ServerError<'a>),
140    Notification {
141        process_id: i32,
142        channel: &'a str,
143        payload: &'a str,
144    },
145    CopyIn {
146        token: Token,
147        binary: bool,
148        column_formats: &'a [u8],
149    },
150    CopyOut {
151        token: Token,
152        binary: bool,
153        column_formats: &'a [u8],
154    },
155    CopyData {
156        token: Token,
157        data: &'a [u8],
158    },
159    CopyDone {
160        token: Token,
161    },
162    Completed {
163        token: Token,
164        outcome: Outcome,
165        transaction: TransactionStatus,
166    },
167    Closed {
168        reason: Error,
169    },
170}
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172enum State {
173    Ssl,
174    Tls,
175    Auth,
176    Scram(bool),
177    Ready,
178    Closing,
179    Closed,
180}
181#[derive(Debug)]
182struct Pending {
183    token: Token,
184    deadline: Option<Instant>,
185    failed: bool,
186    extended: bool,
187    parse: Option<usize>,
188}
189struct Statement {
190    name: String,
191    sql: String,
192    oids: Vec<u32>,
193    parsed: bool,
194}
195/// A parameter is already encoded by the host or `types`; 0=text, 1=binary.
196#[derive(Clone, Copy, Debug)]
197pub struct Parameter<'a> {
198    pub value: Option<&'a [u8]>,
199    pub format: i16,
200}
201
202/// Parameters of one extended-protocol operation. An empty name is uncached.
203#[derive(Clone, Copy, Debug)]
204pub struct ExtendedQuery<'a> {
205    pub name: &'a str,
206    pub sql: &'a str,
207    pub oids: &'a [u32],
208    pub params: &'a [Parameter<'a>],
209    pub result_formats: &'a [i16],
210}
211
212pub struct Connection {
213    config: Config,
214    state: State,
215    input: Vec<u8>,
216    input_at: usize,
217    output: BytesMut,
218    output_at: usize,
219    pending: VecDeque<Pending>,
220    statements: Vec<Statement>,
221    scram: Option<ScramSha256>,
222    auth_ok: bool,
223    tls: bool,
224    copy_in: bool,
225    transaction: TransactionStatus,
226    key: Option<(i32, i32)>,
227    reason: Error,
228}
229impl Connection {
230    pub fn new(config: Config) -> Result<Self> {
231        if config.max_buffer < 1024
232            || config.max_buffer > i32::MAX as usize
233            || config.max_pending == 0
234        {
235            return Err(Error::Limit);
236        }
237        if config.user.contains('\0')
238            || config.database.contains('\0')
239            || config.application_name.contains('\0')
240        {
241            return Err(Error::State("NUL in startup parameter"));
242        }
243        if config.channel_binding_required && config.ssl == SslMode::Disable {
244            return Err(Error::State("channel binding requires TLS"));
245        }
246        let mut this = Self {
247            config,
248            state: State::Auth,
249            input: Vec::with_capacity(8192),
250            input_at: 0,
251            output: BytesMut::with_capacity(8192),
252            output_at: 0,
253            pending: VecDeque::with_capacity(16),
254            statements: Vec::new(),
255            scram: None,
256            auth_ok: false,
257            tls: false,
258            copy_in: false,
259            transaction: TransactionStatus::Idle,
260            key: None,
261            reason: Error::Transport,
262        };
263        if this.config.ssl == SslMode::Disable {
264            this.startup()?;
265        } else {
266            this.state = State::Ssl;
267            frontend::ssl_request(&mut this.output);
268        }
269        Ok(this)
270    }
271    fn startup(&mut self) -> Result<()> {
272        frontend::startup_message(
273            [
274                ("user", self.config.user.as_str()),
275                ("database", self.config.database.as_str()),
276                ("application_name", self.config.application_name.as_str()),
277                ("client_encoding", "UTF8"),
278                ("DateStyle", "ISO"),
279            ],
280            &mut self.output,
281        )?;
282        self.state = State::Auth;
283        Ok(())
284    }
285    pub fn output(&self) -> &[u8] {
286        &self.output[self.output_at..]
287    }
288    pub fn consume_output(&mut self, n: usize) -> Result<()> {
289        if n > self.output().len() {
290            return Err(Error::State("invalid output acknowledgement"));
291        }
292        self.output_at += n;
293        if self.output_at == self.output.len() {
294            self.output.clear();
295            self.output_at = 0;
296        }
297        Ok(())
298    }
299    pub fn receive(&mut self, bytes: &[u8]) -> Result<()> {
300        if matches!(self.state, State::Tls | State::Closing | State::Closed) {
301            return Err(Error::State("connection cannot receive plaintext now"));
302        }
303        let remaining = self.input.len() - self.input_at;
304        if bytes.len() > self.config.max_buffer.saturating_sub(remaining) {
305            self.abort(Error::Limit);
306            return Err(Error::Limit);
307        }
308        if self.input_at != 0 {
309            self.input.copy_within(self.input_at.., 0);
310            self.input.truncate(remaining);
311            self.input_at = 0;
312        }
313        self.input.extend_from_slice(bytes);
314        Ok(())
315    }
316    pub fn tls_established(&mut self) -> Result<()> {
317        if self.state != State::Tls || !self.output().is_empty() {
318            return Err(Error::State("TLS transition not ready"));
319        }
320        self.tls = true;
321        self.startup()
322    }
323    pub fn start_scram(&mut self, scram: ScramSha256) -> Result<()> {
324        let State::Scram(plus) = self.state else {
325            return Err(Error::State("SCRAM was not requested"));
326        };
327        if plus != scram.message().starts_with(b"p=tls-server-end-point,") {
328            return Err(Error::State("SCRAM channel binding mismatch"));
329        }
330        frontend::sasl_initial_response(
331            if plus {
332                "SCRAM-SHA-256-PLUS"
333            } else {
334                "SCRAM-SHA-256"
335            },
336            scram.message(),
337            &mut self.output,
338        )?;
339        self.scram = Some(scram);
340        self.state = State::Auth;
341        Ok(())
342    }
343    fn accept(&self, token: Token) -> Result<()> {
344        if self.state != State::Ready || self.copy_in {
345            return Err(Error::State("Client is not queryable"));
346        }
347        if self.pending.len() >= self.config.max_pending {
348            return Err(Error::Limit);
349        }
350        if self.pending.iter().any(|p| p.token == token) {
351            return Err(Error::State("duplicate operation token"));
352        }
353        Ok(())
354    }
355    fn finish_command(
356        &mut self,
357        token: Token,
358        deadline: Option<Instant>,
359        parse: Option<usize>,
360        before: usize,
361        result: Result<()>,
362        extended: bool,
363    ) -> Result<()> {
364        if let Err(e) = result {
365            self.output.truncate(before);
366            return Err(e);
367        }
368        if self.output.len() > self.config.max_buffer {
369            self.output.truncate(before);
370            return Err(Error::Limit);
371        }
372        self.pending.push_back(Pending {
373            token,
374            deadline,
375            failed: false,
376            extended,
377            parse,
378        });
379        Ok(())
380    }
381    pub fn query(&mut self, token: Token, sql: &str, deadline: Option<Instant>) -> Result<()> {
382        self.accept(token)?;
383        if sql.len().saturating_add(6) > self.config.max_buffer.saturating_sub(self.output.len()) {
384            return Err(Error::Limit);
385        }
386        let before = self.output.len();
387        let result = frontend::query(sql, &mut self.output).map_err(Error::from);
388        self.finish_command(token, deadline, None, before, result, false)
389    }
390    /// Every operation ends in Sync, so an error cannot discard a later token.
391    pub fn execute(
392        &mut self,
393        token: Token,
394        query: ExtendedQuery<'_>,
395        deadline: Option<Instant>,
396    ) -> Result<()> {
397        let ExtendedQuery {
398            name,
399            sql,
400            oids,
401            params,
402            result_formats,
403        } = query;
404        self.accept(token)?;
405        let size = params.iter().fold(
406            64usize
407                .saturating_add(name.len().saturating_mul(2))
408                .saturating_add(sql.len())
409                .saturating_add(oids.len().saturating_mul(4))
410                .saturating_add(result_formats.len().saturating_mul(2)),
411            |n, p| {
412                n.saturating_add(6)
413                    .saturating_add(p.value.map_or(0, <[u8]>::len))
414            },
415        );
416        if size > self.config.max_buffer.saturating_sub(self.output.len()) {
417            return Err(Error::Limit);
418        }
419
420        if params.iter().any(|p| !matches!(p.format, 0 | 1))
421            || result_formats.iter().any(|f| !matches!(f, 0 | 1))
422        {
423            return Err(Error::State("invalid format"));
424        }
425        let index = if name.is_empty() {
426            None
427        } else {
428            self.statements.iter().position(|s| s.name == name)
429        };
430        if let Some(i) = index {
431            let s = &self.statements[i];
432            if s.sql != sql || s.oids != oids {
433                return Err(Error::State(
434                    "Prepared statements must be unique - a different statement was used for this name",
435                ));
436            }
437        }
438        // Refuse reuse until ParseComplete; otherwise a pipelined parse failure
439        // could make a later accepted operation refer to a nonexistent statement.
440        if index.is_some_and(|i| !self.statements[i].parsed) {
441            return Err(Error::State("named statement parse still pending"));
442        }
443        let before = self.output.len();
444        let result = (|| {
445            if index.is_none() {
446                frontend::parse(name, sql, oids.iter().copied(), &mut self.output)?;
447            }
448            frontend::bind(
449                "",
450                name,
451                params.iter().map(|p| p.format),
452                params.iter(),
453                |p, out| {
454                    if let Some(value) = p.value {
455                        out.extend_from_slice(value);
456                        Ok(IsNull::No)
457                    } else {
458                        Ok(IsNull::Yes)
459                    }
460                },
461                result_formats.iter().copied(),
462                &mut self.output,
463            )
464            .map_err(|_| Error::Protocol("invalid Bind message"))?;
465            frontend::describe(b'P', "", &mut self.output)?;
466            frontend::execute("", 0, &mut self.output)?;
467            frontend::sync(&mut self.output);
468            Ok(())
469        })();
470        let new_index = if result.is_ok()
471            && self.output.len() <= self.config.max_buffer
472            && index.is_none()
473            && !name.is_empty()
474        {
475            let i = self.statements.len();
476            self.statements.push(Statement {
477                name: name.into(),
478                sql: sql.into(),
479                oids: oids.into(),
480                parsed: false,
481            });
482            Some(i)
483        } else {
484            None
485        };
486        self.finish_command(token, deadline, new_index, before, result, true)
487    }
488    pub fn copy_data(&mut self, bytes: &[u8]) -> Result<()> {
489        if !self.copy_in {
490            return Err(Error::State("COPY IN is not active"));
491        }
492        if bytes.len().saturating_add(5) > self.config.max_buffer.saturating_sub(self.output.len())
493        {
494            return Err(Error::Limit);
495        }
496        frontend::CopyData::new(bytes)?.write(&mut self.output);
497        Ok(())
498    }
499    pub fn copy_finish(&mut self, error: Option<&str>) -> Result<()> {
500        if !self.copy_in {
501            return Err(Error::State("COPY IN is not active"));
502        }
503        let before = self.output.len();
504        let result = if let Some(message) = error {
505            frontend::copy_fail(message, &mut self.output)
506        } else {
507            frontend::copy_done(&mut self.output);
508            Ok(())
509        };
510        // The earlier Sync is ignored by the server inside COPY IN.
511        // Extended protocol needs a fresh Sync after CopyDone/CopyFail.
512        if result.is_ok() && self.pending.front().is_some_and(|p| p.extended) {
513            frontend::sync(&mut self.output);
514        }
515        if result.is_err() || self.output.len() > self.config.max_buffer {
516            self.output.truncate(before);
517            return Err(Error::Limit);
518        }
519        self.copy_in = false;
520        Ok(())
521    }
522    /// Send on a NEW connection; the main stream remains owned by this state machine.
523    pub fn cancel_request(&self) -> Option<[u8; 16]> {
524        self.key.map(|(pid, key)| {
525            let mut b = [0; 16];
526            b[..4].copy_from_slice(&16u32.to_be_bytes());
527            b[4..8].copy_from_slice(&80877102u32.to_be_bytes());
528            b[8..12].copy_from_slice(&pid.to_be_bytes());
529            b[12..].copy_from_slice(&key.to_be_bytes());
530            b
531        })
532    }
533    pub fn transaction_status(&self) -> TransactionStatus {
534        self.transaction
535    }
536    pub fn is_ready(&self) -> bool {
537        self.state == State::Ready
538    }
539    pub fn pending_count(&self) -> usize {
540        self.pending.len()
541    }
542    pub fn next_timeout(&self) -> Option<Instant> {
543        if matches!(self.state, State::Closing | State::Closed) {
544            return None;
545        }
546        self.pending
547            .iter()
548            .filter_map(|p| p.deadline)
549            .chain(if self.state != State::Ready {
550                self.config.connect_deadline
551            } else {
552                None
553            })
554            .min()
555    }
556    pub fn handle_timeout(&mut self, now: Instant) {
557        if self.next_timeout().is_some_and(|t| t <= now) {
558            self.abort(Error::Timeout);
559        }
560    }
561    /// Transport EOF, TLS failure, cancellation or malformed input terminates all
562    /// pending tokens once. Pull Completed events followed by Closed.
563    pub fn abort(&mut self, reason: Error) {
564        if matches!(self.state, State::Closing | State::Closed) {
565            return;
566        }
567        self.reason = reason;
568        self.state = State::Closing;
569        self.output.clear();
570        self.output_at = 0;
571        self.copy_in = false;
572    }
573    pub fn end(&mut self) -> Result<()> {
574        if !self.pending.is_empty() || self.state != State::Ready {
575            return Err(Error::State("drain queries before end"));
576        }
577        frontend::terminate(&mut self.output);
578        self.state = State::Closing;
579        self.reason = Error::Cancelled;
580        Ok(())
581    }
582    fn token(&self) -> Result<Token> {
583        self.pending
584            .front()
585            .map(|p| p.token)
586            .ok_or(Error::Protocol("unsolicited query response"))
587    }
588    pub fn next_event(&mut self) -> Result<Option<Event<'_>>> {
589        if self.state == State::Closing {
590            if let Some(p) = self.pending.pop_front() {
591                return Ok(Some(Event::Completed {
592                    token: p.token,
593                    outcome: Outcome::Aborted(self.reason),
594                    transaction: self.transaction,
595                }));
596            }
597            if !self.output().is_empty() {
598                return Ok(None);
599            }
600            self.state = State::Closed;
601            return Ok(Some(Event::Closed {
602                reason: self.reason,
603            }));
604        }
605        if matches!(self.state, State::Closed | State::Tls | State::Scram(_)) {
606            return Ok(None);
607        }
608        if self.state == State::Ssl {
609            let Some(&reply) = self.input.get(self.input_at) else {
610                return Ok(None);
611            };
612            self.input_at += 1;
613            match reply {
614                b'S' => {
615                    if self.input.len() != self.input_at {
616                        return Err(Error::Protocol("plaintext after TLS acceptance"));
617                    }
618                    self.state = State::Tls;
619                    return Ok(Some(Event::UpgradeTls));
620                }
621                b'N' if self.config.ssl == SslMode::Prefer => {
622                    self.startup()?;
623                }
624                b'N' => {
625                    return Err(Error::Protocol(
626                        "The server does not support SSL connections",
627                    ));
628                }
629                _ => return Err(Error::Protocol("invalid SSLRequest response")),
630            }
631        }
632        loop {
633            let available = &self.input[self.input_at..];
634            let Some(header) = Header::parse(available)? else {
635                return Ok(None);
636            };
637            if header.len() < 4 {
638                return Err(Error::Protocol("invalid message length"));
639            }
640            let length = header.len() as usize + 1;
641            if length > self.config.max_buffer {
642                return Err(Error::Limit);
643            }
644            if available.len() < length {
645                return Ok(None);
646            }
647            let start = self.input_at + 5;
648            self.input_at += length;
649            let body = &self.input[start..self.input_at];
650            let mut c = Cursor(body);
651            match header.tag() {
652                b'R' if self.state == State::Auth => match c.u32()? {
653                    0 => {
654                        c.end()?;
655                        if self.scram.is_some() {
656                            return Err(Error::Protocol("SCRAM final verification missing"));
657                        }
658                        self.auth_ok = true;
659                    }
660                    3 => {
661                        c.end()?;
662                        if self.config.channel_binding_required {
663                            return Err(Error::Protocol("server did not offer channel binding"));
664                        }
665                        frontend::password_message(&self.config.password, &mut self.output)?;
666                    }
667                    5 => {
668                        let salt = c.take(4)?.try_into().unwrap();
669                        c.end()?;
670                        if self.config.channel_binding_required {
671                            return Err(Error::Protocol("server did not offer channel binding"));
672                        }
673                        let hash =
674                            md5_hash(self.config.user.as_bytes(), &self.config.password, salt);
675                        frontend::password_message(hash.as_bytes(), &mut self.output)?;
676                    }
677                    10 => {
678                        let mut plain = false;
679                        let mut plus = false;
680                        loop {
681                            match c.cstr()? {
682                                "" => break,
683                                "SCRAM-SHA-256" => plain = true,
684                                "SCRAM-SHA-256-PLUS" => plus = true,
685                                _ => {}
686                            }
687                        }
688                        c.end()?;
689                        let plus = self.tls && plus;
690                        if (!plus && !plain) || (self.config.channel_binding_required && !plus) {
691                            return Err(Error::Protocol("unsupported SASL mechanisms"));
692                        }
693                        self.state = State::Scram(plus);
694                        return Ok(Some(Event::ScramNeeded { plus }));
695                    }
696                    11 => {
697                        let iterations = std::str::from_utf8(c.0)
698                            .ok()
699                            .and_then(|s| s.split(',').find_map(|p| p.strip_prefix("i=")))
700                            .and_then(|s| s.parse::<u32>().ok())
701                            .ok_or(Error::Protocol("invalid SCRAM iterations"))?;
702                        if iterations == 0 || iterations > self.config.max_scram_iterations {
703                            return Err(Error::Limit);
704                        }
705                        let scram = self
706                            .scram
707                            .as_mut()
708                            .ok_or(Error::Protocol("unexpected SASL continuation"))?;
709                        scram.update(c.0)?;
710                        frontend::sasl_response(scram.message(), &mut self.output)?;
711                    }
712                    12 => {
713                        let mut scram = self
714                            .scram
715                            .take()
716                            .ok_or(Error::Protocol("unexpected SASL final"))?;
717                        scram.finish(c.0)?;
718                    }
719                    _ => return Err(Error::Protocol("unsupported authentication method")),
720                },
721                b'S' => {
722                    let name = c.cstr()?;
723                    let value = c.cstr()?;
724                    c.end()?;
725                    return Ok(Some(Event::ParameterStatus { name, value }));
726                }
727                b'K' => {
728                    self.key = Some((c.i32()?, c.i32()?));
729                    c.end()?;
730                }
731                b'Z' => {
732                    self.transaction = match c.u8()? {
733                        b'I' => TransactionStatus::Idle,
734                        b'T' => TransactionStatus::InTransaction,
735                        b'E' => TransactionStatus::Failed,
736                        _ => return Err(Error::Protocol("invalid transaction status")),
737                    };
738                    c.end()?;
739                    self.copy_in = false;
740                    if self.state == State::Auth {
741                        if !self.auth_ok {
742                            return Err(Error::Protocol("Ready before authentication"));
743                        }
744                        self.state = State::Ready;
745                        return Ok(Some(Event::Connected));
746                    }
747                    let p = self
748                        .pending
749                        .pop_front()
750                        .ok_or(Error::Protocol("unsolicited ReadyForQuery"))?;
751                    // Keep stable cache indices; failed names can be registered again.
752                    if let Some(i) = p.parse
753                        && !self.statements[i].parsed
754                    {
755                        self.statements[i].name.clear();
756                    }
757                    return Ok(Some(Event::Completed {
758                        token: p.token,
759                        outcome: if p.failed {
760                            Outcome::ServerError
761                        } else {
762                            Outcome::Success
763                        },
764                        transaction: self.transaction,
765                    }));
766                }
767                b'T' => {
768                    return Ok(Some(Event::Fields {
769                        token: self.token()?,
770                        fields: Fields::parse(body)?,
771                    }));
772                }
773                b'D' => {
774                    return Ok(Some(Event::Row {
775                        token: self.token()?,
776                        row: Row::parse(body)?,
777                    }));
778                }
779                b'C' => {
780                    let tag = c.cstr()?;
781                    c.end()?;
782                    let row_count = tag.rsplit(' ').next().and_then(|s| s.parse().ok());
783                    return Ok(Some(Event::CommandComplete {
784                        token: self.token()?,
785                        tag,
786                        row_count,
787                    }));
788                }
789                b'I' => {
790                    c.end()?;
791                    return Ok(Some(Event::CommandComplete {
792                        token: self.token()?,
793                        tag: "",
794                        row_count: None,
795                    }));
796                }
797                b'E' => {
798                    let error = ServerError::parse(body)?;
799                    let token = self.pending.front_mut().map(|p| {
800                        p.failed = true;
801                        p.token
802                    });
803                    if token.is_none()
804                        || matches!(
805                            error.get(b'V').or(error.severity()),
806                            Some("FATAL" | "PANIC")
807                        )
808                    {
809                        self.state = State::Closing;
810                        self.reason = Error::Transport;
811                        self.output.clear();
812                        self.output_at = 0;
813                    }
814                    return Ok(Some(Event::Error { token, error }));
815                }
816                b'N' => return Ok(Some(Event::Notice(ServerError::parse(body)?))),
817                b'A' => {
818                    let process_id = c.i32()?;
819                    let channel = c.cstr()?;
820                    let payload = c.cstr()?;
821                    c.end()?;
822                    return Ok(Some(Event::Notification {
823                        process_id,
824                        channel,
825                        payload,
826                    }));
827                }
828                b'1' => {
829                    c.end()?;
830                    let p = self
831                        .pending
832                        .front_mut()
833                        .ok_or(Error::Protocol("unsolicited ParseComplete"))?;
834                    if let Some(i) = p.parse {
835                        self.statements[i].parsed = true;
836                    }
837                }
838                b'2' | b'3' | b'n' => {
839                    c.end()?;
840                    self.token()?;
841                }
842                b'G' | b'H' => {
843                    let binary = match c.u8()? {
844                        0 => false,
845                        1 => true,
846                        _ => return Err(Error::Protocol("invalid COPY format")),
847                    };
848                    let count = c.u16()? as usize;
849                    let column_formats = c.take(count * 2)?;
850                    c.end()?;
851                    let token = self.token()?;
852                    if header.tag() == b'G' {
853                        if self.pending.len() != 1 {
854                            return Err(Error::Protocol("COPY IN requires an exclusive query"));
855                        }
856                        self.copy_in = true;
857                        return Ok(Some(Event::CopyIn {
858                            token,
859                            binary,
860                            column_formats,
861                        }));
862                    }
863                    return Ok(Some(Event::CopyOut {
864                        token,
865                        binary,
866                        column_formats,
867                    }));
868                }
869                b'd' => {
870                    return Ok(Some(Event::CopyData {
871                        token: self.token()?,
872                        data: body,
873                    }));
874                }
875                b'c' => {
876                    c.end()?;
877                    return Ok(Some(Event::CopyDone {
878                        token: self.token()?,
879                    }));
880                }
881                _ => return Err(Error::Protocol("unexpected backend message")),
882            }
883        }
884    }
885}