Skip to main content

mz_pgwire/
protocol.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::convert::TryFrom;
12use std::future::Future;
13use std::ops::Deref;
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16use std::{iter, mem};
17
18use base64::prelude::*;
19use byteorder::{ByteOrder, NetworkEndian};
20use csv_core::ReadRecordResult;
21use futures::future::{BoxFuture, FutureExt, pending};
22use itertools::Itertools;
23use mz_adapter::client::{RecordFirstRowStream, redact_sql_for_logging};
24use mz_adapter::session::{
25    EndTransactionAction, InProgressRows, LifecycleTimestamps, PortalRefMut, PortalState, Session,
26    SessionConfig, TransactionStatus,
27};
28use mz_adapter::statement_logging::{StatementEndedExecutionReason, StatementExecutionStrategy};
29use mz_adapter::{
30    AdapterError, AdapterNotice, ExecuteContextGuard, ExecuteResponse, ExecutionTime,
31    PeekResponseUnary, metrics, verify_datum_desc,
32};
33use mz_adapter_types::dyncfgs::OIDC_GROUP_CLAIM;
34use mz_auth::Authenticated;
35use mz_auth::password::Password;
36use mz_authenticator::{Authenticator, GenericOidcAuthenticator};
37use mz_frontegg_auth::Authenticator as FronteggAuthenticator;
38use mz_ore::cast::CastFrom;
39use mz_ore::netio::AsyncReady;
40use mz_ore::now::{EpochMillis, SYSTEM_TIME};
41use mz_ore::str::StrExt;
42use mz_ore::{assert_none, assert_ok, instrument, soft_assert_eq_or_log, soft_assert_or_log};
43use mz_pgcopy::{
44    CopyCsvFormatParams, CopyFormatParams, CopyTextFormatParams, csv_blank_line_is_record,
45};
46use mz_pgwire_common::{
47    ConnectionCounter, Cursor, ErrorResponse, Format, FrontendMessage, Severity, VERSION_3,
48    VERSIONS,
49};
50use mz_repr::{
51    CatalogItemId, ColumnIndex, Datum, RelationDesc, RowArena, RowIterator, RowRef,
52    SqlRelationType, SqlScalarType,
53};
54use mz_server_core::TlsMode;
55use mz_server_core::listeners;
56use mz_server_core::listeners::AllowedRoles;
57use mz_sql::ast::display::AstDisplay;
58use mz_sql::ast::{
59    CopyDirection, CopyStatement, CopyTarget, FetchDirection, Ident, Raw, Statement,
60};
61use mz_sql::parse::StatementParseResult;
62use mz_sql::plan::{CopyFormat, ExecuteTimeout, StatementDesc};
63use mz_sql::session::metadata::SessionMetadata;
64use mz_sql::session::user::INTERNAL_USER_NAMES;
65use mz_sql::session::vars::VarInput;
66use postgres::error::SqlState;
67use tokio::io::{self, AsyncRead, AsyncWrite};
68use tokio::select;
69use tokio::time::{self};
70use tokio_metrics::TaskMetrics;
71use tracing::{Instrument, debug, debug_span, info, warn};
72use uuid::Uuid;
73
74use crate::codec::{
75    FramedConn, decode_password, decode_sasl_initial_response, decode_sasl_response,
76};
77use crate::message::{
78    self, BackendMessage, SASLServerFinalMessage, SASLServerFinalMessageKinds,
79    SASLServerFirstMessage,
80};
81
82/// Reports whether the given stream begins with a pgwire handshake.
83///
84/// To avoid false negatives, there must be at least eight bytes in `buf`.
85pub fn match_handshake(buf: &[u8]) -> bool {
86    // The pgwire StartupMessage looks like this:
87    //
88    //     i32 - Length of entire message.
89    //     i32 - Protocol version number.
90    //     [String] - Arbitrary key-value parameters of any length.
91    //
92    // Since arbitrary parameters can be included in the StartupMessage, the
93    // first Int32 is worthless, since the message could have any length.
94    // Instead, we sniff the protocol version number.
95    if buf.len() < 8 {
96        return false;
97    }
98    let version = NetworkEndian::read_i32(&buf[4..8]);
99    VERSIONS.contains(&version)
100}
101
102/// Parameters for the [`run`] function.
103pub struct RunParams<'a, A, I>
104where
105    I: Iterator<Item = TaskMetrics> + Send,
106{
107    /// The TLS mode of the pgwire server.
108    pub tls_mode: Option<TlsMode>,
109    /// A client for the adapter.
110    pub adapter_client: mz_adapter::Client,
111    /// The connection to the client.
112    pub conn: &'a mut FramedConn<A>,
113    /// The universally unique identifier for the connection.
114    pub conn_uuid: Uuid,
115    /// The protocol version that the client provided in the startup message.
116    pub version: i32,
117    /// The parameters that the client provided in the startup message.
118    pub params: BTreeMap<String, String>,
119    /// Frontegg JWT authenticator.
120    pub frontegg: Option<FronteggAuthenticator>,
121    /// OIDC authenticator.
122    pub oidc: GenericOidcAuthenticator,
123    /// The authentication method defined by the server's listener
124    /// configuration.
125    pub authenticator_kind: listeners::AuthenticatorKind,
126    /// Global connection limit and count
127    pub active_connection_counter: ConnectionCounter,
128    /// Helm chart version
129    pub helm_chart_version: Option<String>,
130    /// Whether to allow reserved users (ie: mz_system).
131    pub allowed_roles: AllowedRoles,
132    /// Tokio metrics
133    pub tokio_metrics_intervals: I,
134}
135
136/// Runs a pgwire connection to completion.
137///
138/// This involves responding to `FrontendMessage::StartupMessage` and all future
139/// requests until the client terminates the connection or a fatal error occurs.
140///
141/// Note that this function returns successfully even upon delivering a fatal
142/// error to the client. It only returns `Err` if an unexpected I/O error occurs
143/// while communicating with the client, e.g., if the connection is severed in
144/// the middle of a request.
145#[mz_ore::instrument(level = "debug")]
146pub async fn run<'a, A, I>(
147    RunParams {
148        tls_mode,
149        adapter_client,
150        conn,
151        conn_uuid,
152        version,
153        mut params,
154        frontegg,
155        oidc,
156        authenticator_kind,
157        active_connection_counter,
158        helm_chart_version,
159        allowed_roles,
160        tokio_metrics_intervals,
161    }: RunParams<'a, A, I>,
162) -> Result<(), io::Error>
163where
164    A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin,
165    I: Iterator<Item = TaskMetrics> + Send,
166{
167    if version != VERSION_3 {
168        return conn
169            .send(ErrorResponse::fatal(
170                SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
171                "server does not support the client's requested protocol version",
172            ))
173            .await;
174    }
175
176    let user = params.remove("user").unwrap_or_else(String::new);
177    let options = parse_options(params.get("options").unwrap_or(&String::new()));
178    let authenticator =
179        get_authenticator(authenticator_kind, frontegg, oidc, adapter_client.clone());
180    // TODO move this somewhere it can be shared with HTTP
181    let is_internal_user = INTERNAL_USER_NAMES.contains(&user);
182    // this is a superset of internal users
183    let is_reserved_user = mz_adapter::catalog::is_reserved_role_name(user.as_str());
184    let role_allowed = match allowed_roles {
185        AllowedRoles::Normal => !is_reserved_user,
186        AllowedRoles::Internal => is_internal_user,
187        AllowedRoles::NormalAndInternal => !is_reserved_user || is_internal_user,
188    };
189    if !role_allowed {
190        let msg = format!("unauthorized login to user '{user}'");
191        return conn
192            .send(ErrorResponse::fatal(SqlState::INSUFFICIENT_PRIVILEGE, msg))
193            .await;
194    }
195
196    if let Err(err) = conn.inner().ensure_tls_compatibility(&tls_mode) {
197        return conn.send(err).await;
198    }
199
200    let authenticator_kind = authenticator.kind();
201
202    let (mut session, expired) = match authenticator {
203        Authenticator::Frontegg(frontegg) => {
204            let password = match request_cleartext_password(conn).await {
205                Ok(password) => password,
206                Err(PasswordRequestError::IoError(e)) => return Err(e),
207                Err(PasswordRequestError::InvalidPasswordError(e)) => {
208                    return conn.send(e).await;
209                }
210            };
211
212            let group_claim =
213                OIDC_GROUP_CLAIM.get(adapter_client.get_system_vars().await.dyncfgs());
214            let auth_response = frontegg
215                .authenticate(&user, &password, Some(&group_claim))
216                .await;
217            match auth_response {
218                // Create a session based on the auth session.
219                //
220                // In particular, it's important that the username come from the
221                // auth session, as Frontegg may return an email address with
222                // different casing than the user supplied via the pgwire
223                // username fN
224                Ok((mut auth_session, authenticated)) => {
225                    let groups = auth_session.groups();
226                    let session = adapter_client.new_session(
227                        SessionConfig {
228                            conn_id: conn.conn_id().clone(),
229                            uuid: conn_uuid,
230                            user: auth_session.user().into(),
231                            client_ip: conn.peer_addr().clone(),
232                            external_metadata_rx: Some(auth_session.external_metadata_rx()),
233                            helm_chart_version,
234                            authenticator_kind,
235                            groups,
236                        },
237                        authenticated,
238                    );
239                    let expired = async move { auth_session.expired().await };
240                    (session, expired.left_future())
241                }
242                Err(err) => {
243                    warn!(?err, "pgwire connection failed authentication");
244                    return conn
245                        .send(ErrorResponse::fatal(
246                            SqlState::INVALID_PASSWORD,
247                            "invalid password",
248                        ))
249                        .await;
250                }
251            }
252        }
253        Authenticator::Oidc(oidc) => {
254            // OIDC listener: accepts either a JWT (uses OIDC authentication) or a
255            // plain SQL password (uses SQL password authentication).
256            let password = match request_cleartext_password(conn).await {
257                Ok(password) => password,
258                Err(PasswordRequestError::IoError(e)) => return Err(e),
259                Err(PasswordRequestError::InvalidPasswordError(e)) => {
260                    return conn.send(e).await;
261                }
262            };
263            if is_jwt(&password) {
264                let auth_response = oidc.authenticate(&password, Some(&user)).await;
265                match auth_response {
266                    Ok((mut claims, authenticated)) => {
267                        let groups = claims.groups.take();
268                        let session = adapter_client.new_session(
269                            SessionConfig {
270                                conn_id: conn.conn_id().clone(),
271                                uuid: conn_uuid,
272                                user: std::mem::take(&mut claims.user),
273                                client_ip: conn.peer_addr().clone(),
274                                external_metadata_rx: None,
275                                helm_chart_version,
276                                authenticator_kind,
277                                groups,
278                            },
279                            authenticated,
280                        );
281                        // No invalidation of the auth session once authenticated,
282                        // so auth session lasts indefinitely.
283                        (session, pending().right_future())
284                    }
285                    Err(err) => {
286                        warn!(?err, "pgwire connection failed authentication");
287                        return conn.send(err.into_response()).await;
288                    }
289                }
290            } else {
291                let session = match authenticate_with_password(
292                    conn,
293                    &adapter_client,
294                    user,
295                    Password(password),
296                    conn_uuid,
297                    helm_chart_version,
298                )
299                .await
300                {
301                    Ok(session) => session,
302                    Err(PasswordRequestError::IoError(e)) => return Err(e),
303                    Err(PasswordRequestError::InvalidPasswordError(e)) => {
304                        return conn.send(e).await;
305                    }
306                };
307                (session, pending().right_future())
308            }
309        }
310        Authenticator::Password(adapter_client) => {
311            let password = match request_cleartext_password(conn).await {
312                Ok(password) => password,
313                Err(PasswordRequestError::IoError(e)) => return Err(e),
314                Err(PasswordRequestError::InvalidPasswordError(e)) => {
315                    return conn.send(e).await;
316                }
317            };
318            let session = match authenticate_with_password(
319                conn,
320                &adapter_client,
321                user,
322                Password(password),
323                conn_uuid,
324                helm_chart_version,
325            )
326            .await
327            {
328                Ok(session) => session,
329                Err(PasswordRequestError::IoError(e)) => return Err(e),
330                Err(PasswordRequestError::InvalidPasswordError(e)) => {
331                    return conn.send(e).await;
332                }
333            };
334            // No frontegg check, so auth session lasts indefinitely.
335            (session, pending().right_future())
336        }
337        Authenticator::Sasl(adapter_client) => {
338            // Start the handshake
339            conn.send(BackendMessage::AuthenticationSASL).await?;
340            conn.flush().await?;
341            // Get the initial response indicating chosen mechanism
342            let (mechanism, initial_response) = match conn.recv().await? {
343                Some(FrontendMessage::RawAuthentication(data)) => {
344                    match decode_sasl_initial_response(Cursor::new(&data)).ok() {
345                        Some(FrontendMessage::SASLInitialResponse {
346                            gs2_header,
347                            mechanism,
348                            initial_response,
349                        }) => {
350                            // We do not support channel binding
351                            if gs2_header.channel_binding_enabled() {
352                                return conn
353                                    .send(ErrorResponse::fatal(
354                                        SqlState::PROTOCOL_VIOLATION,
355                                        "channel binding not supported",
356                                    ))
357                                    .await;
358                            }
359                            (mechanism, initial_response)
360                        }
361                        _ => {
362                            return conn
363                                .send(ErrorResponse::fatal(
364                                    SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
365                                    "expected SASLInitialResponse message",
366                                ))
367                                .await;
368                        }
369                    }
370                }
371                _ => {
372                    return conn
373                        .send(ErrorResponse::fatal(
374                            SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
375                            "expected SASLInitialResponse message",
376                        ))
377                        .await;
378                }
379            };
380
381            if mechanism != "SCRAM-SHA-256" {
382                return conn
383                    .send(ErrorResponse::fatal(
384                        SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
385                        "unsupported SASL mechanism",
386                    ))
387                    .await;
388            }
389
390            if initial_response.nonce.len() > 256 {
391                return conn
392                    .send(ErrorResponse::fatal(
393                        SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
394                        "nonce too long",
395                    ))
396                    .await;
397            }
398
399            let (server_first_message_raw, mock_hash) = match adapter_client
400                .generate_sasl_challenge(&user, &initial_response.nonce)
401                .await
402            {
403                Ok(response) => {
404                    let server_first_message_raw = format!(
405                        "r={},s={},i={}",
406                        response.nonce, response.salt, response.iteration_count
407                    );
408
409                    let client_key = [0u8; 32];
410                    let server_key = [1u8; 32];
411                    let mock_hash = format!(
412                        "SCRAM-SHA-256${}:{}${}:{}",
413                        response.iteration_count,
414                        response.salt,
415                        BASE64_STANDARD.encode(client_key),
416                        BASE64_STANDARD.encode(server_key)
417                    );
418
419                    conn.send(BackendMessage::AuthenticationSASLContinue(
420                        SASLServerFirstMessage {
421                            iteration_count: response.iteration_count,
422                            nonce: response.nonce,
423                            salt: response.salt,
424                        },
425                    ))
426                    .await?;
427                    conn.flush().await?;
428                    (server_first_message_raw, mock_hash)
429                }
430                Err(e) => {
431                    return conn.send(e.into_response(Severity::Fatal)).await;
432                }
433            };
434
435            let authenticated = match conn.recv().await? {
436                Some(FrontendMessage::RawAuthentication(data)) => {
437                    match decode_sasl_response(Cursor::new(&data)).ok() {
438                        Some(FrontendMessage::SASLResponse(response)) => {
439                            let auth_message = format!(
440                                "{},{},{}",
441                                initial_response.client_first_message_bare_raw,
442                                server_first_message_raw,
443                                response.client_final_message_bare_raw
444                            );
445                            if response.proof.len() > 1024 {
446                                return conn
447                                    .send(ErrorResponse::fatal(
448                                        SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
449                                        "proof too long",
450                                    ))
451                                    .await;
452                            }
453                            match adapter_client
454                                .verify_sasl_proof(
455                                    &user,
456                                    &response.proof,
457                                    &auth_message,
458                                    &mock_hash,
459                                )
460                                .await
461                            {
462                                Ok((proof_response, authenticated)) => {
463                                    conn.send(BackendMessage::AuthenticationSASLFinal(
464                                        SASLServerFinalMessage {
465                                            kind: SASLServerFinalMessageKinds::Verifier(
466                                                proof_response.verifier,
467                                            ),
468                                            extensions: vec![],
469                                        },
470                                    ))
471                                    .await?;
472                                    conn.flush().await?;
473                                    authenticated
474                                }
475                                Err(_) => {
476                                    return conn
477                                        .send(ErrorResponse::fatal(
478                                            SqlState::INVALID_PASSWORD,
479                                            "invalid password",
480                                        ))
481                                        .await;
482                                }
483                            }
484                        }
485                        _ => {
486                            return conn
487                                .send(ErrorResponse::fatal(
488                                    SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
489                                    "expected SASLResponse message",
490                                ))
491                                .await;
492                        }
493                    }
494                }
495                _ => {
496                    return conn
497                        .send(ErrorResponse::fatal(
498                            SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
499                            "expected SASLResponse message",
500                        ))
501                        .await;
502                }
503            };
504
505            let session = adapter_client.new_session(
506                SessionConfig {
507                    conn_id: conn.conn_id().clone(),
508                    uuid: conn_uuid,
509                    user,
510                    client_ip: conn.peer_addr().clone(),
511                    external_metadata_rx: None,
512                    helm_chart_version,
513                    authenticator_kind,
514                    groups: None,
515                },
516                authenticated,
517            );
518            // No frontegg check, so auth session lasts indefinitely.
519            let auth_session = pending().right_future();
520            (session, auth_session)
521        }
522
523        Authenticator::None => {
524            let session = adapter_client.new_session(
525                SessionConfig {
526                    conn_id: conn.conn_id().clone(),
527                    uuid: conn_uuid,
528                    user,
529                    client_ip: conn.peer_addr().clone(),
530                    external_metadata_rx: None,
531                    helm_chart_version,
532                    authenticator_kind,
533                    groups: None,
534                },
535                Authenticated,
536            );
537            // No frontegg check, so auth session lasts indefinitely.
538            let auth_session = pending().right_future();
539            (session, auth_session)
540        }
541    };
542
543    let system_vars = adapter_client.get_system_vars().await;
544    // Startup parameters that were successfully applied. They additionally
545    // become the session's default values below, once role defaults have been
546    // applied too.
547    let mut applied_params = vec![];
548    for (name, value) in params {
549        let settings = match name.as_str() {
550            "options" => match &options {
551                Ok(opts) => opts,
552                Err(()) => {
553                    session.add_notice(AdapterNotice::BadStartupSetting {
554                        name,
555                        reason: "could not parse".into(),
556                    });
557                    continue;
558                }
559            },
560            _ => &vec![(name, value)],
561        };
562        for (key, val) in settings {
563            const LOCAL: bool = false;
564            // TODO: Issuing an error here is better than what we did before
565            // (silently ignore errors on set), but erroring the connection
566            // might be the better behavior. We maybe need to support more
567            // options sent by psql and drivers before we can safely do this.
568            match session
569                .vars_mut()
570                .set(&system_vars, key, VarInput::Flat(val), LOCAL)
571            {
572                Ok(()) => applied_params.push((key.clone(), val.clone())),
573                Err(err) => {
574                    session.add_notice(AdapterNotice::BadStartupSetting {
575                        name: key.clone(),
576                        reason: err.to_string(),
577                    });
578                }
579            }
580        }
581    }
582    // Otherwise each idle connection retains a full copy of the system variables.
583    drop(system_vars);
584    session
585        .vars_mut()
586        .end_transaction(EndTransactionAction::Commit);
587
588    let _guard = match active_connection_counter.allocate_connection(session.user()) {
589        Ok(drop_connection) => drop_connection,
590        Err(e) => {
591            let e: AdapterError = e.into();
592            return conn.send(e.into_response(Severity::Fatal)).await;
593        }
594    };
595
596    // Register session with adapter.
597    let mut adapter_client = match adapter_client.startup(session).await {
598        Ok(adapter_client) => adapter_client,
599        Err(e) => return conn.send(e.into_response(Severity::Fatal)).await,
600    };
601
602    // Make the startup parameters the session's default values, so that RESET
603    // and DISCARD ALL restore them rather than the server defaults. This
604    // matches PostgreSQL, where client-supplied startup parameters take
605    // precedence over role defaults (which startup registration applied) both
606    // as the current value and as the reset value. Connection poolers rely on
607    // this. For example, pgbouncer's default server_reset_query is DISCARD
608    // ALL, which must not rebind a pooled connection to the default database.
609    for (key, val) in applied_params {
610        if let Err(err) = adapter_client
611            .session()
612            .vars_mut()
613            .set_default(&key, VarInput::Flat(&val))
614        {
615            // Unexpected, since the same value was accepted by set() above.
616            mz_ore::soft_panic_or_log!("failed to apply startup parameter as default: {err:?}");
617        }
618    }
619
620    // Authentication succeeded, so the connection may now carry query traffic,
621    // whose frames are far larger than any credential.
622    conn.allow_post_auth_frames();
623
624    let mut buf = vec![BackendMessage::AuthenticationOk];
625    for var in adapter_client.session().vars().notify_set() {
626        buf.push(BackendMessage::ParameterStatus(var.name(), var.value()));
627    }
628    buf.push(BackendMessage::BackendKeyData {
629        conn_id: adapter_client.session().conn_id().unhandled(),
630        secret_key: adapter_client.session().secret_key(),
631    });
632    buf.extend(
633        adapter_client
634            .session()
635            .drain_notices()
636            .into_iter()
637            .map(|notice| BackendMessage::ErrorResponse(notice.into_response())),
638    );
639    buf.push(BackendMessage::ReadyForQuery(
640        adapter_client.session().transaction().into(),
641    ));
642    conn.send_all(buf).await?;
643    conn.flush().await?;
644
645    let machine = StateMachine {
646        conn,
647        adapter_client,
648        txn_needs_commit: false,
649        reverted_parameters: BTreeMap::new(),
650        tokio_metrics_intervals,
651    };
652
653    select! {
654        r = machine.run() => {
655            // Errors produced internally (like a malformed frame header) should send an
656            // error to the client informing them why the connection was closed. We still want to
657            // return the original error up the stack, though, so we skip error checking during conn
658            // operations.
659            if let Err(err) = &r {
660                let _ = conn
661                    .send(ErrorResponse::fatal(
662                        SqlState::CONNECTION_FAILURE,
663                        err.to_string(),
664                    ))
665                    .await;
666                let _ = conn.flush().await;
667            }
668            r
669        },
670        _ = expired => {
671            conn
672                .send(ErrorResponse::fatal(SqlState::INVALID_AUTHORIZATION_SPECIFICATION, "authentication expired"))
673                .await?;
674            conn.flush().await
675        }
676    }
677}
678
679/// Decides if a given password is a JWT by checking
680/// if we can decode its header.
681fn is_jwt(password: &str) -> bool {
682    jsonwebtoken::decode_header(password).is_ok()
683}
684
685/// Returns (name, value) session settings pairs from an options value.
686///
687/// From Postgres, see pg_split_opts in postinit.c and process_postgres_switches
688/// in postgres.c.
689fn parse_options(value: &str) -> Result<Vec<(String, String)>, ()> {
690    let opts = split_options(value);
691    let mut pairs = Vec::with_capacity(opts.len());
692    let mut seen_prefix = false;
693    for opt in opts {
694        if !seen_prefix {
695            if opt == "-c" {
696                seen_prefix = true;
697            } else {
698                let (key, val) = parse_option(&opt)?;
699                pairs.push((key.to_owned(), val.to_owned()));
700            }
701        } else {
702            let (key, val) = opt.split_once('=').ok_or(())?;
703            pairs.push((key.to_owned(), val.to_owned()));
704            seen_prefix = false;
705        }
706    }
707    Ok(pairs)
708}
709
710/// Returns the parsed key and value from option of the form `--key=value`, `-c
711/// key=value`, or `-ckey=value`. Keys replace `-` with `_`. Returns an error if
712/// there was some other prefix.
713fn parse_option(option: &str) -> Result<(&str, &str), ()> {
714    let (key, value) = option.split_once('=').ok_or(())?;
715    for prefix in &["-c", "--"] {
716        if let Some(key) = key.strip_prefix(prefix) {
717            return Ok((key, value));
718        }
719    }
720    Err(())
721}
722
723/// Splits value by any number of spaces except those preceded by `\`.
724fn split_options(value: &str) -> Vec<String> {
725    let mut strs = Vec::new();
726    // Need to build a string because of the escaping, so we can't simply
727    // subslice into value, and this isn't called enough to need to make it
728    // smart so it only builds a string if needed.
729    let mut current = String::new();
730    let mut was_slash = false;
731    for c in value.chars() {
732        was_slash = match c {
733            ' ' => {
734                if was_slash {
735                    current.push(' ');
736                } else if !current.is_empty() {
737                    // To ignore multiple spaces in a row, only push if current
738                    // is not empty.
739                    strs.push(std::mem::take(&mut current));
740                }
741                false
742            }
743            '\\' => {
744                if was_slash {
745                    // Two slashes in a row will add a slash and not escape the
746                    // next char.
747                    current.push('\\');
748                    false
749                } else {
750                    true
751                }
752            }
753            _ => {
754                current.push(c);
755                false
756            }
757        };
758    }
759    // A `\` at the end will be ignored.
760    if !current.is_empty() {
761        strs.push(current);
762    }
763    strs
764}
765
766enum PasswordRequestError {
767    InvalidPasswordError(ErrorResponse),
768    IoError(io::Error),
769}
770
771impl From<io::Error> for PasswordRequestError {
772    fn from(e: io::Error) -> Self {
773        PasswordRequestError::IoError(e)
774    }
775}
776
777/// Requests a cleartext password from a connection and returns it if it is valid.
778/// Sends an error response in the connection if the password
779/// is not valid.
780async fn request_cleartext_password<A>(
781    conn: &mut FramedConn<A>,
782) -> Result<String, PasswordRequestError>
783where
784    A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin,
785{
786    conn.send(BackendMessage::AuthenticationCleartextPassword)
787        .await?;
788    conn.flush().await?;
789
790    if let Some(message) = conn.recv().await? {
791        if let FrontendMessage::RawAuthentication(data) = message {
792            if let Some(FrontendMessage::Password { password }) =
793                decode_password(Cursor::new(&data)).ok()
794            {
795                return Ok(password);
796            }
797        }
798    }
799
800    Err(PasswordRequestError::InvalidPasswordError(
801        ErrorResponse::fatal(
802            SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
803            "expected Password message",
804        ),
805    ))
806}
807
808/// Helper for password-based authentication using AdapterClient
809/// and returns an authenticated session.
810async fn authenticate_with_password<A>(
811    conn: &FramedConn<A>,
812    adapter_client: &mz_adapter::Client,
813    user: String,
814    password: Password,
815    conn_uuid: Uuid,
816    helm_chart_version: Option<String>,
817) -> Result<Session, PasswordRequestError>
818where
819    A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin,
820{
821    let authenticated = match adapter_client.authenticate(&user, &password).await {
822        Ok(authenticated) => authenticated,
823        Err(err) => {
824            warn!(?err, "pgwire connection failed authentication");
825            return Err(PasswordRequestError::InvalidPasswordError(
826                ErrorResponse::fatal(SqlState::INVALID_PASSWORD, "invalid password"),
827            ));
828        }
829    };
830
831    let session = adapter_client.new_session(
832        SessionConfig {
833            conn_id: conn.conn_id().clone(),
834            uuid: conn_uuid,
835            user,
836            client_ip: conn.peer_addr().clone(),
837            external_metadata_rx: None,
838            helm_chart_version,
839            authenticator_kind: mz_auth::AuthenticatorKind::Password,
840            groups: None,
841        },
842        authenticated,
843    );
844
845    Ok(session)
846}
847
848#[derive(Debug)]
849enum State {
850    Ready,
851    Drain,
852    Done,
853}
854
855struct StateMachine<'a, A, I>
856where
857    I: Iterator<Item = TaskMetrics> + Send + 'a,
858{
859    conn: &'a mut FramedConn<A>,
860    adapter_client: mz_adapter::SessionClient,
861    txn_needs_commit: bool,
862    /// Session parameters that a commit restored, to announce before the next `ReadyForQuery`.
863    reverted_parameters: BTreeMap<&'static str, String>,
864    tokio_metrics_intervals: I,
865}
866
867enum SendRowsEndedReason {
868    Success {
869        result_size: u64,
870        rows_returned: u64,
871    },
872    Errored {
873        error: String,
874    },
875    Canceled,
876}
877
878const ABORTED_TXN_MSG: &str =
879    "current transaction is aborted, commands ignored until end of transaction block";
880
881impl<'a, A, I> StateMachine<'a, A, I>
882where
883    A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin + 'a,
884    I: Iterator<Item = TaskMetrics> + Send + 'a,
885{
886    // Manually desugar this (don't use `async fn run`) here because a much better
887    // error message is produced if there are problems with Send or other traits
888    // somewhere within the Future.
889    #[allow(clippy::manual_async_fn)]
890    #[mz_ore::instrument(level = "debug")]
891    fn run(mut self) -> impl Future<Output = Result<(), io::Error>> + Send + 'a {
892        async move {
893            let mut state = State::Ready;
894            loop {
895                self.send_pending_notices().await?;
896                state = match state {
897                    State::Ready => self.advance_ready().await?,
898                    State::Drain => self.advance_drain().await?,
899                    State::Done => return Ok(()),
900                };
901                self.adapter_client
902                    .add_idle_in_transaction_session_timeout();
903            }
904        }
905    }
906
907    #[instrument(level = "debug")]
908    async fn advance_ready(&mut self) -> Result<State, io::Error> {
909        // Start a new metrics interval before the `recv()` call.
910        self.tokio_metrics_intervals
911            .next()
912            .expect("infinite iterator");
913
914        // Handle timeouts first so we don't execute any statements when there's a pending timeout.
915        let message = select! {
916            biased;
917
918            // `recv_timeout()` is cancel-safe as per it's docs.
919            Some(timeout) = self.adapter_client.recv_timeout() => {
920                let err: AdapterError = timeout.into();
921                let conn_id = self.adapter_client.session().conn_id();
922                tracing::warn!("session timed out, conn_id {}", conn_id);
923
924                // Process the error, doing any state cleanup.
925                let error_response = err.into_response(Severity::Fatal);
926                let error_state = self.send_error_and_get_state(error_response).await;
927
928                // Terminate __after__ we do any cleanup.
929                self.adapter_client.terminate().await;
930
931                // We must wait for the client to send a request before we can send the error response.
932                // Due to the PG wire protocol, we can't send an ErrorResponse unless it is in response
933                // to a client message.
934                let _ = self.conn.recv().await?;
935                return error_state;
936            },
937            // `recv()` is cancel-safe as per it's docs.
938            message = self.conn.recv() => message?,
939        };
940
941        // Take the metrics since just before the `recv`.
942        let interval = self
943            .tokio_metrics_intervals
944            .next()
945            .expect("infinite iterator");
946        let recv_scheduling_delay_ms = interval.total_scheduled_duration.as_secs_f64() * 1000.0;
947
948        // TODO(ggevay): Consider subtracting the scheduling delay from `received`. It's not obvious
949        // whether we should do this, because the result wouldn't exactly correspond to either first
950        // byte received or last byte received (for msgs that arrive in more than one network packet).
951        let received = SYSTEM_TIME();
952
953        self.adapter_client
954            .remove_idle_in_transaction_session_timeout();
955
956        // NOTE(guswynn): we could consider adding spans to all message types. Currently
957        // only a few message types seem useful.
958        let message_name = message.as_ref().map(|m| m.name()).unwrap_or_default();
959
960        if let Some(message) = &message {
961            self.maybe_log_message_arrival(message).await;
962        }
963
964        let start = message.as_ref().map(|_| Instant::now());
965        let next_state = match message {
966            Some(FrontendMessage::Query { sql }) => {
967                let query_root_span =
968                    tracing::info_span!(parent: None, "advance_ready", otel.name = message_name);
969                query_root_span.follows_from(tracing::Span::current());
970                self.query(sql, received)
971                    .instrument(query_root_span)
972                    .await?
973            }
974            Some(FrontendMessage::Parse {
975                name,
976                sql,
977                param_types,
978            }) => self.parse(name, sql, param_types).await?,
979            Some(FrontendMessage::Bind {
980                portal_name,
981                statement_name,
982                param_formats,
983                raw_params,
984                result_formats,
985            }) => {
986                self.bind(
987                    portal_name,
988                    statement_name,
989                    param_formats,
990                    raw_params,
991                    result_formats,
992                )
993                .await?
994            }
995            Some(FrontendMessage::Execute {
996                portal_name,
997                max_rows,
998            }) => {
999                let max_rows = match usize::try_from(max_rows) {
1000                    Ok(0) | Err(_) => ExecuteCount::All, // If `max_rows < 0`, no limit.
1001                    Ok(n) => ExecuteCount::Count(n),
1002                };
1003                let execute_root_span =
1004                    tracing::info_span!(parent: None, "advance_ready", otel.name = message_name);
1005                execute_root_span.follows_from(tracing::Span::current());
1006                let state = self
1007                    .execute(
1008                        portal_name,
1009                        max_rows,
1010                        portal_exec_message,
1011                        None,
1012                        ExecuteTimeout::None,
1013                        None,
1014                        Some(received),
1015                        // The extended protocol commits after `CommandComplete`, at `Sync` or
1016                        // when the next statement starts (`txn_needs_commit` below).
1017                        false,
1018                    )
1019                    .instrument(execute_root_span)
1020                    .await?;
1021                // In PostgreSQL, when using the extended query protocol, some statements may
1022                // trigger an eager commit of the current implicit transaction,
1023                // see: <https://git.postgresql.org/gitweb/?p=postgresql.git&a=commitdiff&h=f92944137>.
1024                //
1025                // In Materialize we instead eagerly commit every implicit transaction that
1026                // cannot take on further statements of the same pipeline, which keeps the
1027                // single-statement optimizations available to queries issued in the extended
1028                // query protocol. The ones that can stay open, so that the pipeline commits
1029                // or rolls back as a unit. See `TransactionStatus::may_span_pipeline`.
1030                //
1031                // We don't immediately commit here to allow users to page through the portal if
1032                // necessary. Committing the transaction would destroy the portal before the next
1033                // Execute command has a chance to resume it. So we instead mark the transaction
1034                // for commit the next time that `ensure_transaction` is called.
1035                let (is_implicit, may_span_pipeline) = {
1036                    let txn = self.adapter_client.session().transaction();
1037                    (txn.is_implicit(), txn.may_span_pipeline())
1038                };
1039                // Ordered so that only a write reads the flag, keeping the catalog
1040                // snapshot off the read path.
1041                let spans_pipeline = may_span_pipeline
1042                    && self
1043                        .adapter_client
1044                        .extended_protocol_implicit_transaction_enabled()
1045                        .await;
1046                if is_implicit && !spans_pipeline {
1047                    self.txn_needs_commit = true;
1048                }
1049                state
1050            }
1051            Some(FrontendMessage::DescribeStatement { name }) => {
1052                self.describe_statement(&name).await?
1053            }
1054            Some(FrontendMessage::DescribePortal { name }) => self.describe_portal(&name).await?,
1055            Some(FrontendMessage::CloseStatement { name }) => self.close_statement(name).await?,
1056            Some(FrontendMessage::ClosePortal { name }) => self.close_portal(name).await?,
1057            Some(FrontendMessage::Flush) => self.flush().await?,
1058            Some(FrontendMessage::Sync) => self.sync().await?,
1059            Some(FrontendMessage::Terminate) => State::Done,
1060
1061            // Accept but ignore stray COPY subprotocol messages, mirroring
1062            // PostgreSQL. Clients stream COPY data optimistically, so when a
1063            // COPY statement fails before COPY mode is entered, its pipelined
1064            // CopyData/CopyDone/CopyFail arrive here. Draining instead would
1065            // discard unrelated messages until the next Sync, hanging simple
1066            // protocol clients that never send one.
1067            Some(FrontendMessage::CopyData(_))
1068            | Some(FrontendMessage::CopyDone)
1069            | Some(FrontendMessage::CopyFail(_)) => State::Ready,
1070
1071            Some(FrontendMessage::Password { .. })
1072            | Some(FrontendMessage::RawAuthentication(_))
1073            | Some(FrontendMessage::SASLInitialResponse { .. })
1074            | Some(FrontendMessage::SASLResponse(_)) => State::Drain,
1075            None => State::Done,
1076        };
1077
1078        if let Some(start) = start {
1079            self.adapter_client
1080                .inner()
1081                .metrics()
1082                .pgwire_message_processing_seconds
1083                .with_label_values(&[message_name])
1084                .observe(start.elapsed().as_secs_f64());
1085        }
1086        self.adapter_client
1087            .inner()
1088            .metrics()
1089            .pgwire_recv_scheduling_delay_ms
1090            .with_label_values(&[message_name])
1091            .observe(recv_scheduling_delay_ms);
1092
1093        Ok(next_state)
1094    }
1095
1096    async fn advance_drain(&mut self) -> Result<State, io::Error> {
1097        let message = self.conn.recv().await?;
1098        if message.is_some() {
1099            self.adapter_client
1100                .remove_idle_in_transaction_session_timeout();
1101        }
1102        match message {
1103            Some(FrontendMessage::Sync) => self.sync().await,
1104            None => Ok(State::Done),
1105            _ => Ok(State::Drain),
1106        }
1107    }
1108
1109    /// Note that `lifecycle_timestamps` belongs to the whole "Simple Query", because the whole
1110    /// Simple Query is received and parsed together. This means that if there are multiple
1111    /// statements in a Simple Query, then all of them have the same `lifecycle_timestamps`.
1112    #[instrument(level = "debug")]
1113    async fn one_query(
1114        &mut self,
1115        stmt: Statement<Raw>,
1116        sql: String,
1117        lifecycle_timestamps: LifecycleTimestamps,
1118        ends_simple_query: bool,
1119    ) -> Result<State, io::Error> {
1120        // Bind the portal. Note that this does not set the empty string prepared
1121        // statement.
1122        const EMPTY_PORTAL: &str = "";
1123        if let Err(e) = self
1124            .adapter_client
1125            .declare(EMPTY_PORTAL.to_string(), stmt, sql)
1126            .await
1127        {
1128            return self
1129                .send_error_and_get_state(e.into_response(Severity::Error))
1130                .await;
1131        }
1132        let portal = self
1133            .adapter_client
1134            .session()
1135            .get_portal_unverified_mut(EMPTY_PORTAL)
1136            .expect("unnamed portal should be present");
1137
1138        *portal.lifecycle_timestamps = Some(lifecycle_timestamps);
1139
1140        let stmt_desc = portal.desc.clone();
1141        if !stmt_desc.param_types.is_empty() {
1142            return self
1143                .send_error_and_get_state(ErrorResponse::error(
1144                    SqlState::UNDEFINED_PARAMETER,
1145                    "there is no parameter $1",
1146                ))
1147                .await;
1148        }
1149
1150        // Maybe send row description.
1151        if let Some(relation_desc) = &stmt_desc.relation_desc {
1152            if !stmt_desc.is_copy {
1153                let formats = vec![Format::Text; stmt_desc.arity()];
1154                self.send(BackendMessage::RowDescription(
1155                    message::encode_row_description(relation_desc, &formats),
1156                ))
1157                .await?;
1158            }
1159        }
1160
1161        let result = match self
1162            .adapter_client
1163            .execute(EMPTY_PORTAL.to_string(), self.conn.wait_closed(), None)
1164            .await
1165        {
1166            Ok((response, execute_started)) => {
1167                self.send_execute_response(
1168                    response,
1169                    stmt_desc.relation_desc,
1170                    EMPTY_PORTAL.to_string(),
1171                    ExecuteCount::All,
1172                    portal_exec_message,
1173                    None,
1174                    ExecuteTimeout::None,
1175                    execute_started,
1176                    ends_simple_query,
1177                )
1178                .await
1179            }
1180            Err(e) => {
1181                self.send_pending_notices().await?;
1182                self.send_error_and_get_state(e.into_response(Severity::Error))
1183                    .await
1184            }
1185        };
1186
1187        // Destroy the portal.
1188        self.adapter_client.session().remove_portal(EMPTY_PORTAL);
1189
1190        result
1191    }
1192
1193    async fn ensure_transaction(
1194        &mut self,
1195        num_stmts: usize,
1196        message_type: &str,
1197    ) -> Result<(), io::Error> {
1198        let start = Instant::now();
1199        if self.txn_needs_commit {
1200            self.commit_transaction().await?;
1201        }
1202        // start_transaction can't error (but assert that just in case it changes in
1203        // the future.
1204        let res = self.adapter_client.start_transaction(Some(num_stmts));
1205        assert_ok!(res);
1206        self.adapter_client
1207            .inner()
1208            .metrics()
1209            .pgwire_ensure_transaction_seconds
1210            .with_label_values(&[message_type])
1211            .observe(start.elapsed().as_secs_f64());
1212        Ok(())
1213    }
1214
1215    /// Logs an arriving frontend message at info level, when
1216    /// `enable_statement_arrival_logging` is on. Runs before the message is
1217    /// processed, so a message whose processing crashes the process still
1218    /// appears in the log. The `kind` field says which message it is, and
1219    /// thereby also whether the statement came in through the simple protocol
1220    /// (`query`) or the extended protocol (`parse`, `bind`, `execute`, ...).
1221    /// The prepared statement and portal names, together with the connection
1222    /// id, allow connecting a `bind` or `execute` back to the `parse` that
1223    /// carried the SQL text.
1224    ///
1225    /// SQL text is parsed and logged with its literals redacted, the same
1226    /// redaction the statement log applies. This means a statement that
1227    /// crashes the parser is not captured, an accepted limitation. Bind
1228    /// parameter values are data that redaction cannot reach, so only their
1229    /// count is logged. Authentication payloads are never logged. COPY data
1230    /// is logged as its length only, and only when it arrives as a stray
1231    /// message in the ready state: messages consumed by the COPY subprotocol
1232    /// or the post-error drain loop don't pass through here at all.
1233    async fn maybe_log_message_arrival(&mut self, message: &FrontendMessage) {
1234        if !self
1235            .adapter_client
1236            .statement_arrival_logging_enabled()
1237            .await
1238        {
1239            return;
1240        }
1241        let session = self.adapter_client.session();
1242        let conn_id = session.conn_id();
1243        let session_uuid = session.uuid();
1244        let kind = message.name();
1245        match message {
1246            FrontendMessage::Query { sql } => {
1247                info!(
1248                    %conn_id, %session_uuid, kind, sql = %redact_sql_for_logging(sql),
1249                    "statement arrival"
1250                );
1251            }
1252            FrontendMessage::Parse { name, sql, .. } => {
1253                info!(
1254                    %conn_id, %session_uuid, kind, name, sql = %redact_sql_for_logging(sql),
1255                    "statement arrival"
1256                );
1257            }
1258            FrontendMessage::Bind {
1259                portal_name,
1260                statement_name,
1261                raw_params,
1262                ..
1263            } => {
1264                info!(
1265                    %conn_id, %session_uuid, kind, portal_name, statement_name,
1266                    num_params = raw_params.len(),
1267                    "statement arrival"
1268                );
1269            }
1270            // COPY payloads would flood the log. Log only their length.
1271            FrontendMessage::CopyData(data) => {
1272                info!(%conn_id, %session_uuid, kind, len = data.len(), "statement arrival");
1273            }
1274            // Authentication payloads must never be logged.
1275            FrontendMessage::Password { .. }
1276            | FrontendMessage::RawAuthentication(_)
1277            | FrontendMessage::SASLInitialResponse { .. }
1278            | FrontendMessage::SASLResponse(_) => {
1279                info!(%conn_id, %session_uuid, kind, "statement arrival");
1280            }
1281            // CopyFail carries a client-supplied free-text error message,
1282            // which we don't log.
1283            FrontendMessage::CopyFail(_) => {
1284                info!(%conn_id, %session_uuid, kind, "statement arrival");
1285            }
1286            // Log the full Debug representation for all other variants, which
1287            // carry only object names or no payload.
1288            FrontendMessage::DescribeStatement { .. }
1289            | FrontendMessage::DescribePortal { .. }
1290            | FrontendMessage::Execute { .. }
1291            | FrontendMessage::Flush
1292            | FrontendMessage::Sync
1293            | FrontendMessage::CloseStatement { .. }
1294            | FrontendMessage::ClosePortal { .. }
1295            | FrontendMessage::Terminate
1296            | FrontendMessage::CopyDone => {
1297                // WARNING: When adding a variant here, consider whether its payload is sensitive or
1298                // bulky!
1299                //
1300                // (The field must not be named `message`, that name is
1301                // reserved for the event text in tracing.)
1302                info!(%conn_id, %session_uuid, kind, contents = ?message, "statement arrival");
1303            }
1304        }
1305    }
1306
1307    fn parse_sql<'b>(&self, sql: &'b str) -> Result<Vec<StatementParseResult<'b>>, ErrorResponse> {
1308        let parse_start = Instant::now();
1309        let result = match self.adapter_client.parse(sql) {
1310            Ok(result) => result.map_err(|e| {
1311                // Convert our 0-based byte position to pgwire's 1-based character
1312                // position.
1313                let pos = sql[..e.error.pos].chars().count() + 1;
1314                ErrorResponse::error(SqlState::SYNTAX_ERROR, e.error.message).with_position(pos)
1315            }),
1316            Err(msg) => Err(ErrorResponse::error(SqlState::PROGRAM_LIMIT_EXCEEDED, msg)),
1317        };
1318        self.adapter_client
1319            .inner()
1320            .metrics()
1321            .parse_seconds
1322            .observe(parse_start.elapsed().as_secs_f64());
1323        result
1324    }
1325
1326    /// Executes a "Simple Query", see
1327    /// <https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-SIMPLE-QUERY>
1328    ///
1329    /// For implicit transaction handling, see "Multiple Statements in a Simple Query" in the above.
1330    #[instrument(level = "debug")]
1331    async fn query(&mut self, sql: String, received: EpochMillis) -> Result<State, io::Error> {
1332        // Parse first before doing any transaction checking.
1333        let stmts = match self.parse_sql(&sql) {
1334            Ok(stmts) => stmts,
1335            Err(err) => {
1336                self.send_error_and_get_state(err).await?;
1337                return self.ready().await;
1338            }
1339        };
1340
1341        let num_stmts = stmts.len();
1342
1343        // Compare with postgres' backend/tcop/postgres.c exec_simple_query.
1344        for (idx, StatementParseResult { ast: stmt, sql }) in stmts.into_iter().enumerate() {
1345            // In an aborted transaction, reject all commands except COMMIT/ROLLBACK.
1346            if self.is_aborted_txn() && !is_txn_exit_stmt(Some(&stmt)) {
1347                self.aborted_txn_error().await?;
1348                break;
1349            }
1350
1351            // Start an implicit transaction if we aren't in any transaction and there's
1352            // more than one statement. This mirrors the `use_implicit_block` variable in
1353            // postgres.
1354            //
1355            // This needs to be done in the loop instead of once at the top because
1356            // a COMMIT/ROLLBACK statement needs to start a new transaction on next
1357            // statement.
1358            self.ensure_transaction(num_stmts, "query").await?;
1359
1360            let ends_simple_query = idx + 1 == num_stmts;
1361            match self
1362                .one_query(
1363                    stmt,
1364                    sql.to_string(),
1365                    LifecycleTimestamps { received },
1366                    ends_simple_query,
1367                )
1368                .await?
1369            {
1370                State::Ready => (),
1371                State::Drain => break,
1372                State::Done => return Ok(State::Done),
1373            }
1374        }
1375
1376        // Implicit transactions are closed at the end of a Query message.
1377        {
1378            if self.adapter_client.session().transaction().is_implicit() {
1379                self.commit_transaction().await?;
1380            }
1381        }
1382
1383        if num_stmts == 0 {
1384            self.send(BackendMessage::EmptyQueryResponse).await?;
1385        }
1386
1387        self.ready().await
1388    }
1389
1390    #[instrument(level = "debug")]
1391    async fn parse(
1392        &mut self,
1393        name: String,
1394        sql: String,
1395        param_oids: Vec<u32>,
1396    ) -> Result<State, io::Error> {
1397        // Start a transaction if we aren't in one.
1398        self.ensure_transaction(1, "parse").await?;
1399
1400        let mut param_types = vec![];
1401        for oid in param_oids {
1402            match mz_pgrepr::Type::from_oid(oid) {
1403                Ok(ty) => match SqlScalarType::try_from(&ty) {
1404                    Ok(ty) => param_types.push(Some(ty)),
1405                    Err(err) => {
1406                        return self
1407                            .send_error_and_get_state(ErrorResponse::error(
1408                                SqlState::INVALID_PARAMETER_VALUE,
1409                                err.to_string(),
1410                            ))
1411                            .await;
1412                    }
1413                },
1414                Err(_) if oid == 0 => param_types.push(None),
1415                Err(e) => {
1416                    return self
1417                        .send_error_and_get_state(ErrorResponse::error(
1418                            SqlState::PROTOCOL_VIOLATION,
1419                            e.to_string(),
1420                        ))
1421                        .await;
1422                }
1423            }
1424        }
1425
1426        let stmts = match self.parse_sql(&sql) {
1427            Ok(stmts) => stmts,
1428            Err(err) => {
1429                return self.send_error_and_get_state(err).await;
1430            }
1431        };
1432        if stmts.len() > 1 {
1433            return self
1434                .send_error_and_get_state(ErrorResponse::error(
1435                    SqlState::INTERNAL_ERROR,
1436                    "cannot insert multiple commands into a prepared statement",
1437                ))
1438                .await;
1439        }
1440        let (maybe_stmt, sql) = match stmts.into_iter().next() {
1441            None => (None, ""),
1442            Some(StatementParseResult { ast, sql }) => (Some(ast), sql),
1443        };
1444        if self.is_aborted_txn() && !is_txn_exit_stmt(maybe_stmt.as_ref()) {
1445            return self.aborted_txn_error().await;
1446        }
1447        match self
1448            .adapter_client
1449            .prepare(name, maybe_stmt, sql.to_string(), param_types)
1450            .await
1451        {
1452            Ok(()) => {
1453                self.send(BackendMessage::ParseComplete).await?;
1454                Ok(State::Ready)
1455            }
1456            Err(e) => {
1457                self.send_error_and_get_state(e.into_response(Severity::Error))
1458                    .await
1459            }
1460        }
1461    }
1462
1463    /// Commits and clears the current transaction.
1464    #[instrument(level = "debug")]
1465    async fn commit_transaction(&mut self) -> Result<(), io::Error> {
1466        self.end_transaction(EndTransactionAction::Commit).await
1467    }
1468
1469    /// Rollback and clears the current transaction.
1470    #[instrument(level = "debug")]
1471    async fn rollback_transaction(&mut self) -> Result<(), io::Error> {
1472        self.end_transaction(EndTransactionAction::Rollback).await
1473    }
1474
1475    /// End a transaction and report to the user if an error occurred.
1476    ///
1477    /// The parameters this changes must be announced, exactly as an explicit
1478    /// `COMMIT`/`ROLLBACK` announces them. Otherwise a `SET LOCAL` outside an
1479    /// explicit transaction announces its new value and never its revert, and a
1480    /// client that caches parameters keeps the reverted value.
1481    #[instrument(level = "debug")]
1482    async fn end_transaction(&mut self, action: EndTransactionAction) -> Result<(), io::Error> {
1483        self.txn_needs_commit = false;
1484        match self.adapter_client.end_transaction(action).await {
1485            Ok(
1486                ExecuteResponse::TransactionCommitted { params }
1487                | ExecuteResponse::TransactionRolledBack { params },
1488            ) => {
1489                self.send_parameter_statuses(params).await?;
1490            }
1491            Ok(_) => {}
1492            Err(err) if action == EndTransactionAction::Commit => {
1493                self.send(BackendMessage::ErrorResponse(
1494                    err.into_response(Severity::Error),
1495                ))
1496                .await?;
1497            }
1498            // We only roll back after an error was already sent, and a client expects just one
1499            // error per failed query.
1500            Err(_) => {}
1501        }
1502        Ok(())
1503    }
1504
1505    /// Settles a statement, or a step of one, right before its completion message
1506    /// (`CommandComplete` or `PortalSuspended`). If `ends_simple_query`, the statement is the last
1507    /// of a simple query, and its implicit transaction commits now. Returns the commit's error,
1508    /// which takes the place of the completion message. The parameters that the commit reverts are
1509    /// announced before the next `ReadyForQuery`.
1510    async fn settle_statement(&mut self, ends_simple_query: bool) -> Option<ErrorResponse> {
1511        match self
1512            .adapter_client
1513            .settle_statement(ends_simple_query)
1514            .await
1515        {
1516            Ok(settled) => {
1517                self.reverted_parameters.extend(settled.reverted);
1518                None
1519            }
1520            Err(err) => Some(err.into_response(Severity::Error)),
1521        }
1522    }
1523
1524    async fn send_execution_time(&mut self, time: Option<ExecutionTime>) -> Result<(), io::Error> {
1525        if let Some(notice) =
1526            time.and_then(|time| self.adapter_client.session().execution_time_notice(time))
1527        {
1528            self.send(notice.into_response()).await?;
1529        }
1530        Ok(())
1531    }
1532
1533    /// Announces changed parameters, restricted to those the client is told
1534    /// about at startup.
1535    #[instrument(level = "debug")]
1536    async fn send_parameter_statuses(
1537        &mut self,
1538        params: BTreeMap<&'static str, String>,
1539    ) -> Result<(), io::Error> {
1540        let notify_set: mz_ore::collections::HashSet<String> = self
1541            .adapter_client
1542            .session()
1543            .vars()
1544            .notify_set()
1545            .map(|v| v.name().to_string())
1546            .collect();
1547
1548        for (name, value) in params
1549            .into_iter()
1550            .filter(|(name, _value)| notify_set.contains(*name))
1551        {
1552            self.send(BackendMessage::ParameterStatus(name, value))
1553                .await?;
1554        }
1555        Ok(())
1556    }
1557
1558    #[instrument(level = "debug")]
1559    async fn bind(
1560        &mut self,
1561        portal_name: String,
1562        statement_name: String,
1563        param_formats: Vec<Format>,
1564        raw_params: Vec<Option<Vec<u8>>>,
1565        result_formats: Vec<Format>,
1566    ) -> Result<State, io::Error> {
1567        // Start a transaction if we aren't in one.
1568        self.ensure_transaction(1, "bind").await?;
1569
1570        let aborted_txn = self.is_aborted_txn();
1571        let stmt = match self
1572            .adapter_client
1573            .get_prepared_statement(&statement_name)
1574            .await
1575        {
1576            Ok(stmt) => stmt,
1577            Err(err) => {
1578                return self
1579                    .send_error_and_get_state(err.into_response(Severity::Error))
1580                    .await;
1581            }
1582        };
1583
1584        let param_types = &stmt.desc().param_types;
1585        if param_types.len() != raw_params.len() {
1586            let message = format!(
1587                "bind message supplies {actual} parameters, \
1588                 but prepared statement \"{name}\" requires {expected}",
1589                name = statement_name,
1590                actual = raw_params.len(),
1591                expected = param_types.len()
1592            );
1593            return self
1594                .send_error_and_get_state(ErrorResponse::error(
1595                    SqlState::PROTOCOL_VIOLATION,
1596                    message,
1597                ))
1598                .await;
1599        }
1600        let param_formats = match pad_formats(param_formats, raw_params.len()) {
1601            Ok(param_formats) => param_formats,
1602            Err(msg) => {
1603                return self
1604                    .send_error_and_get_state(ErrorResponse::error(
1605                        SqlState::PROTOCOL_VIOLATION,
1606                        msg,
1607                    ))
1608                    .await;
1609            }
1610        };
1611        if aborted_txn && !is_txn_exit_stmt(stmt.stmt()) {
1612            return self.aborted_txn_error().await;
1613        }
1614        let buf = RowArena::new();
1615        let mut params = vec![];
1616        for ((raw_param, mz_typ), format) in raw_params
1617            .into_iter()
1618            .zip_eq(param_types)
1619            .zip_eq(param_formats)
1620        {
1621            let pg_typ = mz_pgrepr::Type::from(mz_typ);
1622            let datum = match raw_param {
1623                None => Datum::Null,
1624                Some(bytes) => match mz_pgrepr::Value::decode(format, &pg_typ, &bytes) {
1625                    Ok(param) => match param.into_datum_decode_error(&buf, &pg_typ, "parameter") {
1626                        Ok(datum) => datum,
1627                        Err(msg) => {
1628                            return self
1629                                .send_error_and_get_state(ErrorResponse::error(
1630                                    SqlState::INVALID_PARAMETER_VALUE,
1631                                    msg,
1632                                ))
1633                                .await;
1634                        }
1635                    },
1636                    Err(err) => {
1637                        // NUL characters get the same SQLSTATE that PostgreSQL
1638                        // reports for them.
1639                        let (code, msg) = if err.is::<mz_pgrepr::NulCharacterError>() {
1640                            (SqlState::CHARACTER_NOT_IN_REPERTOIRE, err.to_string())
1641                        } else {
1642                            (
1643                                SqlState::INVALID_PARAMETER_VALUE,
1644                                format!("unable to decode parameter: {}", err),
1645                            )
1646                        };
1647                        return self
1648                            .send_error_and_get_state(ErrorResponse::error(code, msg))
1649                            .await;
1650                    }
1651                },
1652            };
1653            params.push((datum, mz_typ.clone()))
1654        }
1655
1656        let result_formats = match pad_formats(
1657            result_formats,
1658            stmt.desc()
1659                .relation_desc
1660                .clone()
1661                .map(|desc| desc.typ().column_types.len())
1662                .unwrap_or(0),
1663        ) {
1664            Ok(result_formats) => result_formats,
1665            Err(msg) => {
1666                return self
1667                    .send_error_and_get_state(ErrorResponse::error(
1668                        SqlState::PROTOCOL_VIOLATION,
1669                        msg,
1670                    ))
1671                    .await;
1672            }
1673        };
1674
1675        // Binary encodings are disabled for list, map, and aclitem types, but this doesn't
1676        // apply to COPY TO statements.
1677        if !stmt.stmt().map_or(false, |stmt| match stmt {
1678            Statement::Copy(CopyStatement {
1679                direction: CopyDirection::To,
1680                ..
1681            }) => true,
1682            Statement::Copy(CopyStatement {
1683                direction: CopyDirection::From,
1684                // To be conservative, we are restricting COPY FROM to only allow list/map/aclitem types if it is not
1685                // copying from STDIN. It is likely that this works in theory, but is risky and likely to OOM anyways
1686                // as all the data will be held in a buffer in memory before being processed.
1687                target: CopyTarget::Expr(_),
1688                ..
1689            }) => true,
1690            _ => false,
1691        }) {
1692            if let Some(desc) = stmt.desc().relation_desc.clone() {
1693                for (format, ty) in result_formats.iter().zip_eq(desc.iter_types()) {
1694                    if let Format::Binary = format {
1695                        if let Err(msg) = mz_pgrepr::Value::binary_encoding_error(&ty.scalar_type) {
1696                            return self
1697                                .send_error_and_get_state(ErrorResponse::error(
1698                                    SqlState::UNDEFINED_FUNCTION,
1699                                    msg,
1700                                ))
1701                                .await;
1702                        }
1703                    }
1704                }
1705            }
1706        }
1707
1708        let desc = stmt.desc().clone();
1709        let logging = Arc::clone(stmt.logging());
1710        let stmt_ast = stmt.stmt().cloned();
1711        let state_revision = stmt.state_revision;
1712        if let Err(err) = self.adapter_client.session().set_portal(
1713            portal_name,
1714            desc,
1715            stmt_ast,
1716            logging,
1717            params,
1718            result_formats,
1719            state_revision,
1720        ) {
1721            return self
1722                .send_error_and_get_state(err.into_response(Severity::Error))
1723                .await;
1724        }
1725
1726        self.send(BackendMessage::BindComplete).await?;
1727        Ok(State::Ready)
1728    }
1729
1730    /// `outer_ctx_extra` is Some when we are executing as part of an outer statement, e.g., a FETCH
1731    /// triggering the execution of the underlying query.
1732    fn execute(
1733        &mut self,
1734        portal_name: String,
1735        max_rows: ExecuteCount,
1736        get_response: GetResponse,
1737        fetch_portal_name: Option<String>,
1738        timeout: ExecuteTimeout,
1739        outer_ctx_extra: Option<ExecuteContextGuard>,
1740        received: Option<EpochMillis>,
1741        ends_simple_query: bool,
1742    ) -> BoxFuture<'_, Result<State, io::Error>> {
1743        async move {
1744            let aborted_txn = self.is_aborted_txn();
1745
1746            // Check if the portal has been started and can be continued.
1747            let portal = match self
1748                .adapter_client
1749                .session()
1750                .get_portal_unverified_mut(&portal_name)
1751            {
1752                Some(portal) => portal,
1753                None => {
1754                    let msg = format!("portal {} does not exist", portal_name.quoted());
1755                    if let Some(outer_ctx_extra) = outer_ctx_extra {
1756                        self.adapter_client.retire_execute(
1757                            outer_ctx_extra,
1758                            StatementEndedExecutionReason::Errored { error: msg.clone() },
1759                        );
1760                    }
1761                    return self
1762                        .send_error_and_get_state(ErrorResponse::error(
1763                            SqlState::INVALID_CURSOR_NAME,
1764                            msg,
1765                        ))
1766                        .await;
1767                }
1768            };
1769
1770            *portal.lifecycle_timestamps = received.map(LifecycleTimestamps::new);
1771
1772            // In an aborted transaction, reject all commands except COMMIT/ROLLBACK.
1773            let txn_exit_stmt = is_txn_exit_stmt(portal.stmt.as_deref());
1774            if aborted_txn && !txn_exit_stmt {
1775                if let Some(outer_ctx_extra) = outer_ctx_extra {
1776                    self.adapter_client.retire_execute(
1777                        outer_ctx_extra,
1778                        StatementEndedExecutionReason::Errored {
1779                            error: ABORTED_TXN_MSG.to_string(),
1780                        },
1781                    );
1782                }
1783                return self.aborted_txn_error().await;
1784            }
1785
1786            let row_desc = portal.desc.relation_desc.clone();
1787            match portal.state {
1788                PortalState::NotStarted => {
1789                    // Start a transaction if we aren't in one.
1790                    self.ensure_transaction(1, "execute").await?;
1791                    match self
1792                        .adapter_client
1793                        .execute(
1794                            portal_name.clone(),
1795                            self.conn.wait_closed(),
1796                            outer_ctx_extra,
1797                        )
1798                        .await
1799                    {
1800                        Ok((response, execute_started)) => {
1801                            self.send_execute_response(
1802                                response,
1803                                row_desc,
1804                                portal_name,
1805                                max_rows,
1806                                get_response,
1807                                fetch_portal_name,
1808                                timeout,
1809                                execute_started,
1810                                ends_simple_query,
1811                            )
1812                            .await
1813                        }
1814                        Err(e) => {
1815                            self.send_pending_notices().await?;
1816                            self.send_error_and_get_state(e.into_response(Severity::Error))
1817                                .await
1818                        }
1819                    }
1820                }
1821                PortalState::InProgress(rows) => {
1822                    let rows = rows.take().expect("InProgress rows must be populated");
1823                    let (result, statement_ended_execution_reason) = match self
1824                        .send_rows(
1825                            row_desc.expect("portal missing row desc on resumption"),
1826                            portal_name,
1827                            rows,
1828                            max_rows,
1829                            get_response,
1830                            fetch_portal_name,
1831                            timeout,
1832                            ends_simple_query,
1833                        )
1834                        .await
1835                    {
1836                        Err(e) => {
1837                            // This is an error communicating with the connection.
1838                            // We consider that to be a cancelation, rather than a query error.
1839                            (Err(e), StatementEndedExecutionReason::Canceled)
1840                        }
1841                        Ok((ok, SendRowsEndedReason::Canceled)) => {
1842                            (Ok(ok), StatementEndedExecutionReason::Canceled)
1843                        }
1844                        // NOTE: For now the values for `result_size` and
1845                        // `rows_returned` in fetches are a bit confusing.
1846                        // We record `Some(n)` for the first fetch, where `n` is
1847                        // the number of bytes/rows returned by the inner
1848                        // execute (regardless of how many rows the
1849                        // fetch fetched), and `None` for subsequent fetches.
1850                        //
1851                        // This arguably makes sense since the size/rows
1852                        // returned measures how much work the compute
1853                        // layer had to do to satisfy the query, but
1854                        // we should revisit it if/when we start
1855                        // logging the inner execute separately.
1856                        Ok((
1857                            ok,
1858                            SendRowsEndedReason::Success {
1859                                result_size: _,
1860                                rows_returned: _,
1861                            },
1862                        )) => (
1863                            Ok(ok),
1864                            StatementEndedExecutionReason::Success {
1865                                result_size: None,
1866                                rows_returned: None,
1867                                execution_strategy: None,
1868                            },
1869                        ),
1870                        Ok((ok, SendRowsEndedReason::Errored { error })) => {
1871                            (Ok(ok), StatementEndedExecutionReason::Errored { error })
1872                        }
1873                    };
1874                    if let Some(outer_ctx_extra) = outer_ctx_extra {
1875                        self.adapter_client
1876                            .retire_execute(outer_ctx_extra, statement_ended_execution_reason);
1877                    }
1878                    result
1879                }
1880                // FETCH is an awkward command for our current architecture. In Postgres it
1881                // will extract <count> rows from the target portal, cache them, and return
1882                // them to the user as requested. Its command tag is always FETCH <num rows
1883                // extracted>. In Materialize, since we have chosen to not fully support FETCH,
1884                // we must remember the number of rows that were returned. Use this tag to
1885                // remember that information and return it.
1886                PortalState::Completed(Some(tag)) => {
1887                    let tag = tag.to_string();
1888                    if let Some(outer_ctx_extra) = outer_ctx_extra {
1889                        self.adapter_client.retire_execute(
1890                            outer_ctx_extra,
1891                            StatementEndedExecutionReason::Success {
1892                                result_size: None,
1893                                rows_returned: None,
1894                                execution_strategy: None,
1895                            },
1896                        );
1897                    }
1898                    if let Some(err) = self.settle_statement(ends_simple_query).await {
1899                        return self.send_error_and_get_state(err).await;
1900                    }
1901                    self.send(BackendMessage::CommandComplete { tag }).await?;
1902                    Ok(State::Ready)
1903                }
1904                PortalState::Completed(None) => {
1905                    let error = format!(
1906                        "portal {} cannot be run",
1907                        Ident::new_unchecked(portal_name).to_ast_string_stable()
1908                    );
1909                    if let Some(outer_ctx_extra) = outer_ctx_extra {
1910                        self.adapter_client.retire_execute(
1911                            outer_ctx_extra,
1912                            StatementEndedExecutionReason::Errored {
1913                                error: error.clone(),
1914                            },
1915                        );
1916                    }
1917                    self.send_error_and_get_state(ErrorResponse::error(
1918                        SqlState::OBJECT_NOT_IN_PREREQUISITE_STATE,
1919                        error,
1920                    ))
1921                    .await
1922                }
1923            }
1924        }
1925        .instrument(debug_span!("execute"))
1926        .boxed()
1927    }
1928
1929    #[instrument(level = "debug")]
1930    async fn describe_statement(&mut self, name: &str) -> Result<State, io::Error> {
1931        // Start a transaction if we aren't in one.
1932        self.ensure_transaction(1, "describe_statement").await?;
1933
1934        let stmt = match self.adapter_client.get_prepared_statement(name).await {
1935            Ok(stmt) => stmt,
1936            Err(err) => {
1937                return self
1938                    .send_error_and_get_state(err.into_response(Severity::Error))
1939                    .await;
1940            }
1941        };
1942        // Cloning to avoid a mutable borrow issue because `send` also uses `adapter_client`
1943        let parameter_desc = BackendMessage::ParameterDescription(
1944            stmt.desc()
1945                .param_types
1946                .iter()
1947                .map(mz_pgrepr::Type::from)
1948                .collect(),
1949        );
1950        // Claim that all results will be output in text format, even
1951        // though the true result formats are not yet known. A bit
1952        // weird, but this is the behavior that PostgreSQL specifies.
1953        let formats = vec![Format::Text; stmt.desc().arity()];
1954        let row_desc = describe_rows(stmt.desc(), &formats);
1955        self.send_all([parameter_desc, row_desc]).await?;
1956        Ok(State::Ready)
1957    }
1958
1959    #[instrument(level = "debug")]
1960    async fn describe_portal(&mut self, name: &str) -> Result<State, io::Error> {
1961        // Start a transaction if we aren't in one.
1962        self.ensure_transaction(1, "describe_portal").await?;
1963
1964        let session = self.adapter_client.session();
1965        let row_desc = session
1966            .get_portal_unverified(name)
1967            .map(|portal| describe_rows(&portal.desc, &portal.result_formats));
1968        match row_desc {
1969            Some(row_desc) => {
1970                self.send(row_desc).await?;
1971                Ok(State::Ready)
1972            }
1973            None => {
1974                self.send_error_and_get_state(ErrorResponse::error(
1975                    SqlState::INVALID_CURSOR_NAME,
1976                    format!("portal {} does not exist", name.quoted()),
1977                ))
1978                .await
1979            }
1980        }
1981    }
1982
1983    #[instrument(level = "debug")]
1984    async fn close_statement(&mut self, name: String) -> Result<State, io::Error> {
1985        self.adapter_client
1986            .session()
1987            .remove_prepared_statement(&name);
1988        self.send(BackendMessage::CloseComplete).await?;
1989        Ok(State::Ready)
1990    }
1991
1992    #[instrument(level = "debug")]
1993    async fn close_portal(&mut self, name: String) -> Result<State, io::Error> {
1994        self.adapter_client.session().remove_portal(&name);
1995        self.send(BackendMessage::CloseComplete).await?;
1996        Ok(State::Ready)
1997    }
1998
1999    /// Completes the portal that carried a `CLOSE`.
2000    ///
2001    /// The `CLOSE` can name that very portal, and sequencing has then already
2002    /// removed it. Marking the state is bookkeeping for a portal nobody will
2003    /// read again, so its absence is expected rather than an error.
2004    fn complete_portal_after_close(&mut self, name: &str) {
2005        if let Some(portal) = self
2006            .adapter_client
2007            .session()
2008            .get_portal_unverified_mut(name)
2009        {
2010            *portal.state = PortalState::Completed(None);
2011        }
2012    }
2013
2014    /// Completes the portal that carried a `DECLARE`.
2015    ///
2016    /// A successful `DECLARE` only ever adds a portal, and adding one under a
2017    /// name already in use fails with `DuplicateCursor`, so the executing portal
2018    /// is still present here.
2019    fn complete_portal_after_declare(&mut self, name: &str) {
2020        match self
2021            .adapter_client
2022            .session()
2023            .get_portal_unverified_mut(name)
2024        {
2025            Some(portal) => *portal.state = PortalState::Completed(None),
2026            None => {
2027                mz_ore::soft_panic_or_log!("portal {} vanished across a DECLARE", name.quoted())
2028            }
2029        }
2030    }
2031
2032    async fn fetch(
2033        &mut self,
2034        name: String,
2035        count: Option<FetchDirection>,
2036        max_rows: ExecuteCount,
2037        fetch_portal_name: Option<String>,
2038        timeout: ExecuteTimeout,
2039        ctx_extra: ExecuteContextGuard,
2040        ends_simple_query: bool,
2041    ) -> Result<State, io::Error> {
2042        // Unlike Execute, no count specified in FETCH returns 1 row, and 0 means 0
2043        // instead of All.
2044        let count = count.unwrap_or(FetchDirection::ForwardCount(1));
2045
2046        // Figure out how many rows we should send back by looking at the various
2047        // combinations of the execute and fetch.
2048        //
2049        // In Postgres, Fetch will cache <count> rows from the target portal and
2050        // return those as requested (if, say, an Execute message was sent with a
2051        // max_rows < the Fetch's count). We expect that case to be incredibly rare and
2052        // so have chosen to not support it until users request it. This eases
2053        // implementation difficulty since we don't have to be able to "send" rows to
2054        // a buffer.
2055        //
2056        // TODO(mjibson): Test this somehow? Need to divide up the pgtest files in
2057        // order to have some that are not Postgres compatible.
2058        let count = match (max_rows, count) {
2059            (ExecuteCount::Count(max_rows), FetchDirection::ForwardCount(count)) => {
2060                let count = usize::cast_from(count);
2061                if max_rows < count {
2062                    let msg = "Execute with max_rows < a FETCH's count is not supported";
2063                    self.adapter_client.retire_execute(
2064                        ctx_extra,
2065                        StatementEndedExecutionReason::Errored {
2066                            error: msg.to_string(),
2067                        },
2068                    );
2069                    return self
2070                        .send_error_and_get_state(ErrorResponse::error(
2071                            SqlState::FEATURE_NOT_SUPPORTED,
2072                            msg,
2073                        ))
2074                        .await;
2075                }
2076                ExecuteCount::Count(count)
2077            }
2078            (ExecuteCount::Count(_), FetchDirection::ForwardAll) => {
2079                let msg = "Execute with max_rows of a FETCH ALL is not supported";
2080                self.adapter_client.retire_execute(
2081                    ctx_extra,
2082                    StatementEndedExecutionReason::Errored {
2083                        error: msg.to_string(),
2084                    },
2085                );
2086                return self
2087                    .send_error_and_get_state(ErrorResponse::error(
2088                        SqlState::FEATURE_NOT_SUPPORTED,
2089                        msg,
2090                    ))
2091                    .await;
2092            }
2093            (ExecuteCount::All, FetchDirection::ForwardAll) => ExecuteCount::All,
2094            (ExecuteCount::All, FetchDirection::ForwardCount(count)) => {
2095                ExecuteCount::Count(usize::cast_from(count))
2096            }
2097        };
2098        let cursor_name = name.to_string();
2099        self.execute(
2100            cursor_name,
2101            count,
2102            fetch_message,
2103            fetch_portal_name,
2104            timeout,
2105            Some(ctx_extra),
2106            None,
2107            ends_simple_query,
2108        )
2109        .await
2110    }
2111
2112    async fn flush(&mut self) -> Result<State, io::Error> {
2113        self.conn.flush().await?;
2114        Ok(State::Ready)
2115    }
2116
2117    /// Sends a backend message to the client, after applying a severity filter.
2118    ///
2119    /// The message is only sent if its severity is above the severity set
2120    /// in the session, with the default value being NOTICE.
2121    #[instrument(level = "debug")]
2122    async fn send<M>(&mut self, message: M) -> Result<(), io::Error>
2123    where
2124        M: Into<BackendMessage>,
2125    {
2126        let message: BackendMessage = message.into();
2127        let is_error =
2128            matches!(&message, BackendMessage::ErrorResponse(e) if e.severity.is_error());
2129
2130        self.conn.send(message).await?;
2131
2132        // Flush immediately after sending an error response, as some clients
2133        // expect to be able to read the error response before sending a Sync
2134        // message. This is arguably in violation of the protocol specification,
2135        // but the specification is somewhat ambiguous, and easier to match
2136        // PostgreSQL here than to fix all the clients that have this
2137        // expectation.
2138        if is_error {
2139            self.conn.flush().await?;
2140        }
2141
2142        Ok(())
2143    }
2144
2145    #[instrument(level = "debug")]
2146    pub async fn send_all(
2147        &mut self,
2148        messages: impl IntoIterator<Item = BackendMessage>,
2149    ) -> Result<(), io::Error> {
2150        for m in messages {
2151            self.send(m).await?;
2152        }
2153        Ok(())
2154    }
2155
2156    #[instrument(level = "debug")]
2157    async fn sync(&mut self) -> Result<State, io::Error> {
2158        // Close the current transaction if we are in an implicit transaction.
2159        if self.adapter_client.session().transaction().is_implicit() {
2160            self.commit_transaction().await?;
2161        }
2162        self.ready().await
2163    }
2164
2165    #[instrument(level = "debug")]
2166    async fn ready(&mut self) -> Result<State, io::Error> {
2167        let reverted_parameters = mem::take(&mut self.reverted_parameters);
2168        self.send_parameter_statuses(reverted_parameters).await?;
2169        let txn_state = self.adapter_client.session().transaction().into();
2170        self.send(BackendMessage::ReadyForQuery(txn_state)).await?;
2171        self.flush().await
2172    }
2173
2174    #[allow(clippy::too_many_arguments)]
2175    #[instrument(level = "debug")]
2176    async fn send_execute_response(
2177        &mut self,
2178        response: ExecuteResponse,
2179        row_desc: Option<RelationDesc>,
2180        portal_name: String,
2181        max_rows: ExecuteCount,
2182        get_response: GetResponse,
2183        fetch_portal_name: Option<String>,
2184        timeout: ExecuteTimeout,
2185        execute_started: Instant,
2186        ends_simple_query: bool,
2187    ) -> Result<State, io::Error> {
2188        let execution_time = self
2189            .adapter_client
2190            .session()
2191            .maybe_mark_staged(ExecutionTime::completed(execute_started.elapsed()));
2192        self.send_pending_notices().await?;
2193        let mut tag = response.tag();
2194
2195        macro_rules! command_complete {
2196            () => {{
2197                if let Some(err) = self.settle_statement(ends_simple_query).await {
2198                    return self.send_error_and_get_state(err).await;
2199                }
2200                self.send_execution_time(Some(execution_time)).await?;
2201                self.send(BackendMessage::CommandComplete {
2202                    tag: tag
2203                        .take()
2204                        .expect("command_complete only called on tag-generating results"),
2205                })
2206                .await?;
2207                Ok(State::Ready)
2208            }};
2209        }
2210
2211        let r = match response {
2212            ExecuteResponse::ClosedCursor => {
2213                self.complete_portal_after_close(&portal_name);
2214                command_complete!()
2215            }
2216            ExecuteResponse::DeclaredCursor => {
2217                self.complete_portal_after_declare(&portal_name);
2218                command_complete!()
2219            }
2220            ExecuteResponse::EmptyQuery => {
2221                self.send(BackendMessage::EmptyQueryResponse).await?;
2222                Ok(State::Ready)
2223            }
2224            ExecuteResponse::Fetch {
2225                name,
2226                count,
2227                timeout,
2228                ctx_extra,
2229            } => {
2230                self.fetch(
2231                    name,
2232                    count,
2233                    max_rows,
2234                    Some(portal_name.to_string()),
2235                    timeout,
2236                    ctx_extra,
2237                    ends_simple_query,
2238                )
2239                .await
2240            }
2241            ExecuteResponse::SendingRowsStreaming {
2242                rows,
2243                instance_id,
2244                strategy,
2245            } => {
2246                let row_desc = row_desc
2247                    .expect("missing row description for ExecuteResponse::SendingRowsStreaming");
2248
2249                let span = tracing::debug_span!("sending_rows_streaming");
2250
2251                self.send_rows(
2252                    row_desc,
2253                    portal_name,
2254                    InProgressRows::new(RecordFirstRowStream::new(
2255                        Box::new(rows),
2256                        execute_started,
2257                        &self.adapter_client,
2258                        Some(instance_id),
2259                        Some(strategy),
2260                    )),
2261                    max_rows,
2262                    get_response,
2263                    fetch_portal_name,
2264                    timeout,
2265                    ends_simple_query,
2266                )
2267                .instrument(span)
2268                .await
2269                .map(|(state, _)| state)
2270            }
2271            ExecuteResponse::SendingRowsImmediate { rows } => {
2272                let row_desc = row_desc
2273                    .expect("missing row description for ExecuteResponse::SendingRowsImmediate");
2274
2275                let span = tracing::debug_span!("sending_rows_immediate");
2276
2277                let stream =
2278                    futures::stream::once(futures::future::ready(PeekResponseUnary::Rows(rows)));
2279                self.send_rows(
2280                    row_desc,
2281                    portal_name,
2282                    InProgressRows::new(RecordFirstRowStream::new(
2283                        Box::new(stream),
2284                        execute_started,
2285                        &self.adapter_client,
2286                        None,
2287                        Some(StatementExecutionStrategy::Constant),
2288                    )),
2289                    max_rows,
2290                    get_response,
2291                    fetch_portal_name,
2292                    timeout,
2293                    ends_simple_query,
2294                )
2295                .instrument(span)
2296                .await
2297                .map(|(state, _)| state)
2298            }
2299            ExecuteResponse::SetVariable { name, .. } => {
2300                // This code is somewhat awkwardly structured because we
2301                // can't hold `var` across an await point.
2302                let qn = name.to_string();
2303                let msg = if let Some(var) = self
2304                    .adapter_client
2305                    .session()
2306                    .vars_mut()
2307                    .notify_set()
2308                    .find(|v| v.name() == qn)
2309                {
2310                    Some(BackendMessage::ParameterStatus(var.name(), var.value()))
2311                } else {
2312                    None
2313                };
2314                if let Some(msg) = msg {
2315                    self.send(msg).await?;
2316                }
2317                command_complete!()
2318            }
2319            ExecuteResponse::Subscribing {
2320                rx,
2321                ctx_extra,
2322                instance_id,
2323            } => {
2324                if fetch_portal_name.is_none() {
2325                    let mut msg = ErrorResponse::notice(
2326                        SqlState::WARNING,
2327                        "streaming SUBSCRIBE rows directly requires a client that does not buffer output",
2328                    );
2329                    if self.adapter_client.session().vars().application_name() == "psql" {
2330                        msg.hint = Some(
2331                            "Wrap your SUBSCRIBE statement in `COPY (SUBSCRIBE ...) TO STDOUT`."
2332                                .into(),
2333                        )
2334                    }
2335                    self.send(msg).await?;
2336                    self.conn.flush().await?;
2337                }
2338                let row_desc =
2339                    row_desc.expect("missing row description for ExecuteResponse::Subscribing");
2340                let (result, statement_ended_execution_reason) = match self
2341                    .send_rows(
2342                        row_desc,
2343                        portal_name,
2344                        InProgressRows::new(
2345                            RecordFirstRowStream::new(
2346                                rx,
2347                                execute_started,
2348                                &self.adapter_client,
2349                                Some(instance_id),
2350                                None,
2351                            )
2352                            .without_execution_time(),
2353                        ),
2354                        max_rows,
2355                        get_response,
2356                        fetch_portal_name,
2357                        timeout,
2358                        ends_simple_query,
2359                    )
2360                    .await
2361                {
2362                    Err(e) => {
2363                        // This is an error communicating with the connection.
2364                        // We consider that to be a cancelation, rather than a query error.
2365                        (Err(e), StatementEndedExecutionReason::Canceled)
2366                    }
2367                    Ok((ok, SendRowsEndedReason::Canceled)) => {
2368                        (Ok(ok), StatementEndedExecutionReason::Canceled)
2369                    }
2370                    Ok((
2371                        ok,
2372                        SendRowsEndedReason::Success {
2373                            result_size,
2374                            rows_returned,
2375                        },
2376                    )) => (
2377                        Ok(ok),
2378                        StatementEndedExecutionReason::Success {
2379                            result_size: Some(result_size),
2380                            rows_returned: Some(rows_returned),
2381                            execution_strategy: None,
2382                        },
2383                    ),
2384                    Ok((ok, SendRowsEndedReason::Errored { error })) => {
2385                        (Ok(ok), StatementEndedExecutionReason::Errored { error })
2386                    }
2387                };
2388                self.adapter_client
2389                    .retire_execute(ctx_extra, statement_ended_execution_reason);
2390                return result;
2391            }
2392            ExecuteResponse::CopyTo { format, resp } => {
2393                let row_desc =
2394                    row_desc.expect("missing row description for ExecuteResponse::CopyTo");
2395                match *resp {
2396                    ExecuteResponse::Subscribing {
2397                        rx,
2398                        ctx_extra,
2399                        instance_id,
2400                    } => {
2401                        let (result, statement_ended_execution_reason) = match self
2402                            .copy_rows(
2403                                format,
2404                                row_desc,
2405                                RecordFirstRowStream::new(
2406                                    rx,
2407                                    execute_started,
2408                                    &self.adapter_client,
2409                                    Some(instance_id),
2410                                    None,
2411                                ),
2412                                ends_simple_query,
2413                            )
2414                            .await
2415                        {
2416                            Err(e) => {
2417                                // This is an error communicating with the connection.
2418                                // We consider that to be a cancelation, rather than a query error.
2419                                (Err(e), StatementEndedExecutionReason::Canceled)
2420                            }
2421                            Ok((
2422                                state,
2423                                SendRowsEndedReason::Success {
2424                                    result_size,
2425                                    rows_returned,
2426                                },
2427                            )) => (
2428                                Ok(state),
2429                                StatementEndedExecutionReason::Success {
2430                                    result_size: Some(result_size),
2431                                    rows_returned: Some(rows_returned),
2432                                    execution_strategy: None,
2433                                },
2434                            ),
2435                            Ok((state, SendRowsEndedReason::Errored { error })) => {
2436                                (Ok(state), StatementEndedExecutionReason::Errored { error })
2437                            }
2438                            Ok((state, SendRowsEndedReason::Canceled)) => {
2439                                (Ok(state), StatementEndedExecutionReason::Canceled)
2440                            }
2441                        };
2442                        self.adapter_client
2443                            .retire_execute(ctx_extra, statement_ended_execution_reason);
2444                        return result;
2445                    }
2446                    ExecuteResponse::SendingRowsStreaming {
2447                        rows,
2448                        instance_id,
2449                        strategy,
2450                    } => {
2451                        // We don't need to finalize execution here;
2452                        // it was already done in the
2453                        // coordinator. Just extract the state and
2454                        // return that.
2455                        return self
2456                            .copy_rows(
2457                                format,
2458                                row_desc,
2459                                RecordFirstRowStream::new(
2460                                    Box::new(rows),
2461                                    execute_started,
2462                                    &self.adapter_client,
2463                                    Some(instance_id),
2464                                    Some(strategy),
2465                                ),
2466                                ends_simple_query,
2467                            )
2468                            .await
2469                            .map(|(state, _)| state);
2470                    }
2471                    ExecuteResponse::SendingRowsImmediate { rows } => {
2472                        let span = tracing::debug_span!("sending_rows_immediate");
2473
2474                        let rows = futures::stream::once(futures::future::ready(
2475                            PeekResponseUnary::Rows(rows),
2476                        ));
2477                        // We don't need to finalize execution here;
2478                        // it was already done in the
2479                        // coordinator. Just extract the state and
2480                        // return that.
2481                        return self
2482                            .copy_rows(
2483                                format,
2484                                row_desc,
2485                                RecordFirstRowStream::new(
2486                                    Box::new(rows),
2487                                    execute_started,
2488                                    &self.adapter_client,
2489                                    None,
2490                                    Some(StatementExecutionStrategy::Constant),
2491                                ),
2492                                ends_simple_query,
2493                            )
2494                            .instrument(span)
2495                            .await
2496                            .map(|(state, _)| state);
2497                    }
2498                    _ => {
2499                        return self
2500                            .send_error_and_get_state(ErrorResponse::error(
2501                                SqlState::INTERNAL_ERROR,
2502                                "unsupported COPY response type".to_string(),
2503                            ))
2504                            .await;
2505                    }
2506                };
2507            }
2508            ExecuteResponse::CopyFrom {
2509                target_id,
2510                target_name,
2511                columns,
2512                params,
2513                ctx_extra,
2514            } => {
2515                let row_desc =
2516                    row_desc.expect("missing row description for ExecuteResponse::CopyFrom");
2517                self.copy_from(
2518                    target_id,
2519                    target_name,
2520                    columns,
2521                    params,
2522                    row_desc,
2523                    ctx_extra,
2524                    ends_simple_query,
2525                )
2526                .await
2527            }
2528            ExecuteResponse::TransactionCommitted { params }
2529            | ExecuteResponse::TransactionRolledBack { params }
2530            | ExecuteResponse::DiscardedAll { params } => {
2531                self.send_parameter_statuses(params).await?;
2532                command_complete!()
2533            }
2534
2535            ExecuteResponse::AlteredDefaultPrivileges
2536            | ExecuteResponse::AlteredObject(..)
2537            | ExecuteResponse::AlteredRole
2538            | ExecuteResponse::AlteredSystemConfiguration
2539            | ExecuteResponse::CreatedCluster { .. }
2540            | ExecuteResponse::CreatedClusterReplica { .. }
2541            | ExecuteResponse::CreatedConnection { .. }
2542            | ExecuteResponse::CreatedDatabase { .. }
2543            | ExecuteResponse::CreatedIndex { .. }
2544            | ExecuteResponse::CreatedMetricSink { .. }
2545            | ExecuteResponse::CreatedIntrospectionSubscribe
2546            | ExecuteResponse::CreatedMaterializedView { .. }
2547            | ExecuteResponse::CreatedRole
2548            | ExecuteResponse::CreatedSchema { .. }
2549            | ExecuteResponse::CreatedSecret { .. }
2550            | ExecuteResponse::CreatedSink { .. }
2551            | ExecuteResponse::CreatedSource { .. }
2552            | ExecuteResponse::CreatedTable { .. }
2553            | ExecuteResponse::CreatedType
2554            | ExecuteResponse::CreatedView { .. }
2555            | ExecuteResponse::CreatedViews { .. }
2556            | ExecuteResponse::CreatedNetworkPolicy
2557            | ExecuteResponse::CreatedQueryPolicy
2558            | ExecuteResponse::Comment
2559            | ExecuteResponse::Deallocate { .. }
2560            | ExecuteResponse::Deleted(..)
2561            | ExecuteResponse::DiscardedTemp
2562            | ExecuteResponse::DroppedObject(_)
2563            | ExecuteResponse::DroppedOwned
2564            | ExecuteResponse::GrantedPrivilege
2565            | ExecuteResponse::GrantedRole
2566            | ExecuteResponse::Inserted(..)
2567            | ExecuteResponse::Copied(..)
2568            | ExecuteResponse::Prepare
2569            | ExecuteResponse::Raised
2570            | ExecuteResponse::ReassignOwned
2571            | ExecuteResponse::RevokedPrivilege
2572            | ExecuteResponse::RevokedRole
2573            | ExecuteResponse::StartedTransaction { .. }
2574            | ExecuteResponse::Updated(..)
2575            | ExecuteResponse::ValidatedConnection => {
2576                command_complete!()
2577            }
2578        };
2579
2580        assert_none!(tag, "tag created but not consumed: {:?}", tag);
2581        r
2582    }
2583
2584    #[allow(clippy::too_many_arguments)]
2585    // TODO(guswynn): figure out how to get it to compile without skip_all
2586    #[mz_ore::instrument(level = "debug")]
2587    async fn send_rows(
2588        &mut self,
2589        row_desc: RelationDesc,
2590        portal_name: String,
2591        mut rows: InProgressRows,
2592        max_rows: ExecuteCount,
2593        get_response: GetResponse,
2594        fetch_portal_name: Option<String>,
2595        timeout: ExecuteTimeout,
2596        ends_simple_query: bool,
2597    ) -> Result<(State, SendRowsEndedReason), io::Error> {
2598        // If this portal is being executed from a FETCH then we need to use the result
2599        // format type of the outer portal.
2600        let result_format_portal_name: &str = if let Some(ref name) = fetch_portal_name {
2601            name
2602        } else {
2603            &portal_name
2604        };
2605        let result_formats = self
2606            .adapter_client
2607            .session()
2608            .get_portal_unverified(result_format_portal_name)
2609            .expect("valid fetch portal name for send rows")
2610            .result_formats
2611            .clone();
2612
2613        let (mut wait_once, mut deadline) = match timeout {
2614            ExecuteTimeout::None => (false, None),
2615            ExecuteTimeout::Seconds(t) => (
2616                false,
2617                Some(tokio::time::Instant::now() + tokio::time::Duration::from_secs_f64(t)),
2618            ),
2619            ExecuteTimeout::WaitOnce => (true, None),
2620        };
2621
2622        // Sanity check that the various `RelationDesc`s match up.
2623        {
2624            let portal_name_desc = &self
2625                .adapter_client
2626                .session()
2627                .get_portal_unverified(portal_name.as_str())
2628                .expect("portal should exist")
2629                .desc
2630                .relation_desc;
2631            if let Some(portal_name_desc) = portal_name_desc {
2632                soft_assert_eq_or_log!(portal_name_desc, &row_desc);
2633            }
2634            if let Some(fetch_portal_name) = &fetch_portal_name {
2635                let fetch_portal_desc = &self
2636                    .adapter_client
2637                    .session()
2638                    .get_portal_unverified(fetch_portal_name)
2639                    .expect("portal should exist")
2640                    .desc
2641                    .relation_desc;
2642                if let Some(fetch_portal_desc) = fetch_portal_desc {
2643                    soft_assert_eq_or_log!(fetch_portal_desc, &row_desc);
2644                }
2645            }
2646        }
2647
2648        self.conn.set_encode_state(
2649            row_desc
2650                .typ()
2651                .column_types
2652                .iter()
2653                .map(|ty| mz_pgrepr::Type::from(&ty.scalar_type))
2654                .zip_eq(result_formats)
2655                .collect(),
2656            self.adapter_client.session().vars().text_encode_settings(),
2657        );
2658
2659        let mut total_sent_rows = 0;
2660        let mut total_sent_bytes = 0;
2661        // want_rows is the maximum number of rows the client wants.
2662        let mut want_rows = match max_rows {
2663            ExecuteCount::All => usize::MAX,
2664            ExecuteCount::Count(count) => count,
2665        };
2666
2667        let mut rows_buffered = false;
2668        // Send rows while the client still wants them and there are still rows to send.
2669        loop {
2670            // Fetch next batch of rows, waiting for a possible requested
2671            // timeout or notice.
2672            let batch = if rows.current.is_some() {
2673                FetchResult::Rows(rows.current.take())
2674            } else if want_rows == 0 {
2675                FetchResult::Rows(None)
2676            } else {
2677                let notice_fut = self.adapter_client.session().recv_notice();
2678                // Biased: drain available data before checking the deadline.
2679                // This is critical for the WaitOnce case, where the deadline
2680                // is set to `Instant::now()` right after the first batch:
2681                // without `biased`, `recv()` and the already-expired deadline
2682                // race nondeterministically, so we might break the loop
2683                // before `no_more_rows` is set (or even before ready rows
2684                // are consumed). With an explicit `TIMEOUT`, missing a batch
2685                // right at the boundary is acceptable, but WaitOnce fires
2686                // immediately and the race is not.
2687                //
2688                // Trade-off: if `recv()` keeps returning Ready (unlikely in
2689                // practice—row processing + flush is slower than upstream
2690                // tick granularity), a `TIMEOUT` deadline could be delayed.
2691                // See database-issues#9470.
2692                tokio::select! {
2693                    biased;
2694                    err = self.conn.wait_closed() => return Err(err),
2695                    batch = rows.remaining.recv() => match batch {
2696                        None => FetchResult::Rows(None),
2697                        Some(PeekResponseUnary::Rows(rows)) => FetchResult::Rows(Some(rows)),
2698                        Some(PeekResponseUnary::Error(err)) => {
2699                            FetchResult::Error(err.into_response(Severity::Error))
2700                        }
2701                        Some(PeekResponseUnary::DependencyDropped(dep)) => {
2702                            FetchResult::Error(
2703                                dep.to_concurrent_dependency_drop()
2704                                    .into_response(Severity::Error),
2705                            )
2706                        }
2707                        Some(PeekResponseUnary::Canceled) => FetchResult::Canceled,
2708                    },
2709                    notice = notice_fut => {
2710                        FetchResult::Notice(notice)
2711                    }
2712                    _ = time::sleep_until(
2713                        deadline.unwrap_or_else(tokio::time::Instant::now),
2714                    ), if deadline.is_some() => FetchResult::Rows(None),
2715                    // Flush buffered rows before waiting for the next batch. If EOF is
2716                    // ready, the protocol can flush the final rows with the response.
2717                    _ = std::future::ready(()), if rows_buffered => FetchResult::FlushRows,
2718                }
2719            };
2720
2721            match batch {
2722                FetchResult::Rows(None) => break,
2723                FetchResult::Rows(Some(mut batch_rows)) => {
2724                    if let Err(err) = verify_datum_desc(&row_desc, &mut batch_rows) {
2725                        let msg = err.to_string();
2726                        return self
2727                            .send_error_and_get_state(err.into_response(Severity::Error))
2728                            .await
2729                            .map(|state| (state, SendRowsEndedReason::Errored { error: msg }));
2730                    }
2731
2732                    // If wait_once is true: the first time this fn is called it blocks (same as
2733                    // deadline == None). The second time this fn is called it should behave the
2734                    // same a 0s timeout.
2735                    if wait_once && batch_rows.peek().is_some() {
2736                        deadline = Some(tokio::time::Instant::now());
2737                        wait_once = false;
2738                    }
2739
2740                    // Send a portion of the rows.
2741                    let mut sent_rows = 0;
2742                    let mut sent_bytes = 0;
2743                    let messages = (&mut batch_rows)
2744                        // TODO(parkmycar): This is a fair bit of juggling between iterator types
2745                        // to count the total number of bytes. Alternatively we could track the
2746                        // total sent bytes in this .map(...) call, but having side effects in map
2747                        // is a code smell.
2748                        .map(|row| {
2749                            let row_len = row.byte_len();
2750                            let values = mz_pgrepr::values_from_row(row, row_desc.typ());
2751                            (row_len, BackendMessage::DataRow(values))
2752                        })
2753                        .inspect(|(row_len, _)| {
2754                            sent_bytes += row_len;
2755                            sent_rows += 1
2756                        })
2757                        .map(|(_row_len, row)| row)
2758                        .take(want_rows);
2759                    self.send_all(messages).await?;
2760
2761                    rows_buffered |= sent_rows > 0;
2762                    total_sent_rows += sent_rows;
2763                    total_sent_bytes += sent_bytes;
2764                    want_rows -= sent_rows;
2765
2766                    // If we have sent the number of requested rows, put the remainder of the batch
2767                    // (if any) back and stop sending.
2768                    if want_rows == 0 {
2769                        if batch_rows.peek().is_some() {
2770                            rows.current = Some(batch_rows);
2771                        }
2772                        break;
2773                    }
2774                }
2775                FetchResult::FlushRows => {
2776                    self.conn.flush().await?;
2777                    rows_buffered = false;
2778                }
2779                FetchResult::Notice(notice) => {
2780                    self.send(notice.into_response()).await?;
2781                    self.conn.flush().await?;
2782                    rows_buffered = false;
2783                }
2784                FetchResult::Error(err) => {
2785                    let text = err.message.clone();
2786                    return self
2787                        .send_error_and_get_state(err)
2788                        .await
2789                        .map(|state| (state, SendRowsEndedReason::Errored { error: text }));
2790                }
2791                FetchResult::Canceled => {
2792                    return self
2793                        .send_error_and_get_state(ErrorResponse::error(
2794                            SqlState::QUERY_CANCELED,
2795                            "canceling statement due to user request",
2796                        ))
2797                        .await
2798                        .map(|state| (state, SendRowsEndedReason::Canceled));
2799                }
2800            }
2801        }
2802
2803        let execution_time = rows
2804            .remaining
2805            .take_execution_time()
2806            .map(|time| self.adapter_client.session().maybe_mark_staged(time));
2807        let portal = self
2808            .adapter_client
2809            .session()
2810            .get_portal_unverified_mut(&portal_name)
2811            .expect("valid portal name for send rows");
2812
2813        let saw_rows = rows.remaining.saw_rows;
2814        let no_more_rows = rows.no_more_rows();
2815        let metric_recorded = rows.remaining.metric_recorded;
2816        let recorded_first_row_instant = rows.remaining.recorded_first_row_instant;
2817
2818        if no_more_rows && !metric_recorded {
2819            rows.remaining.metric_recorded = true;
2820        }
2821
2822        // Always return rows back, even if it's empty. This prevents an unclosed
2823        // portal from re-executing after it has been emptied.
2824        *portal.state = PortalState::InProgress(Some(rows));
2825
2826        let fetch_portal = fetch_portal_name.map(|name| {
2827            self.adapter_client
2828                .session()
2829                .get_portal_unverified_mut(&name)
2830                .expect("valid fetch portal")
2831        });
2832        let response_message = get_response(max_rows, total_sent_rows, fetch_portal);
2833        // Attend to metrics if there are no more rows. Only record once per stream
2834        // to avoid polluting the histogram when an exhausted cursor is FETCHed again.
2835        if no_more_rows && !metric_recorded {
2836            let statement_type = if let Some(stmt) = &self
2837                .adapter_client
2838                .session()
2839                .get_portal_unverified(&portal_name)
2840                .expect("valid portal name for send_rows")
2841                .stmt
2842            {
2843                metrics::statement_type_label_value(stmt.deref())
2844            } else {
2845                "no-statement"
2846            };
2847            let duration = if saw_rows {
2848                recorded_first_row_instant
2849                    .expect("recorded_first_row_instant because saw_rows")
2850                    .elapsed()
2851            } else {
2852                // If the result is empty, then we define time from first to last row as 0.
2853                // (Note that, currently, an empty result involves a PeekResponse with 0 rows, which
2854                // does flip `saw_rows`, so this code path is currently not exercised.)
2855                Duration::ZERO
2856            };
2857            self.adapter_client
2858                .inner()
2859                .metrics()
2860                .result_rows_first_to_last_byte_seconds
2861                .with_label_values(&[statement_type])
2862                .observe(duration.as_secs_f64());
2863        }
2864
2865        // Committing clears the session's portals, so this comes after their last use above.
2866        let state = match self.settle_statement(ends_simple_query).await {
2867            Some(err) => self.send_error_and_get_state(err).await?,
2868            None => {
2869                self.send_execution_time(execution_time).await?;
2870                self.send(response_message).await?;
2871                State::Ready
2872            }
2873        };
2874
2875        Ok((
2876            state,
2877            SendRowsEndedReason::Success {
2878                result_size: u64::cast_from(total_sent_bytes),
2879                rows_returned: u64::cast_from(total_sent_rows),
2880            },
2881        ))
2882    }
2883
2884    #[mz_ore::instrument(level = "debug")]
2885    async fn copy_rows(
2886        &mut self,
2887        format: CopyFormat,
2888        row_desc: RelationDesc,
2889        mut stream: RecordFirstRowStream,
2890        ends_simple_query: bool,
2891    ) -> Result<(State, SendRowsEndedReason), io::Error> {
2892        let (row_format, encode_format) = match format {
2893            CopyFormat::Text => (
2894                CopyFormatParams::Text(CopyTextFormatParams::default()),
2895                Format::Text,
2896            ),
2897            CopyFormat::Binary => (CopyFormatParams::Binary, Format::Binary),
2898            CopyFormat::Csv => (
2899                CopyFormatParams::Csv(CopyCsvFormatParams::default()),
2900                Format::Text,
2901            ),
2902            CopyFormat::Parquet => {
2903                let text = "Parquet format is not supported".to_string();
2904                return self
2905                    .send_error_and_get_state(ErrorResponse::error(
2906                        SqlState::INTERNAL_ERROR,
2907                        text.clone(),
2908                    ))
2909                    .await
2910                    .map(|state| (state, SendRowsEndedReason::Errored { error: text }));
2911            }
2912        };
2913
2914        // Binary encoding is not implemented for some types (e.g., list, map,
2915        // and aclitem). Unlike the extended query protocol's Bind handler, COPY
2916        // does not validate this when binding the portal: the portal's result
2917        // formats describe the `CopyData` wrapper, not the COPY format itself,
2918        // so the Bind handler explicitly skips `COPY TO` statements. We must
2919        // therefore check here, before streaming any rows, otherwise
2920        // `encode_binary` would panic mid-stream (SQL-323).
2921        if let CopyFormat::Binary = format {
2922            if let Some(msg) = row_desc
2923                .iter_types()
2924                .find_map(|ty| mz_pgrepr::Value::binary_encoding_error(&ty.scalar_type).err())
2925            {
2926                return self
2927                    .send_error_and_get_state(ErrorResponse::error(
2928                        SqlState::UNDEFINED_FUNCTION,
2929                        msg,
2930                    ))
2931                    .await
2932                    .map(|state| {
2933                        (
2934                            state,
2935                            SendRowsEndedReason::Errored {
2936                                error: msg.to_string(),
2937                            },
2938                        )
2939                    });
2940            }
2941        }
2942
2943        // Unlike `COPY TO <external destination>`, which is encoded in the
2944        // dataflow layer, `COPY TO STDOUT` runs in the session and so honors
2945        // the session's encoding settings, matching PostgreSQL.
2946        let text_settings = self.adapter_client.session().vars().text_encode_settings();
2947        let encode_fn = |row: &RowRef, typ: &SqlRelationType, out: &mut Vec<u8>| {
2948            mz_pgcopy::encode_copy_format(&row_format, row, typ, out, text_settings)
2949        };
2950
2951        let typ = row_desc.typ();
2952        let column_formats = iter::repeat(encode_format)
2953            .take(typ.column_types.len())
2954            .collect();
2955        self.send(BackendMessage::CopyOutResponse {
2956            overall_format: encode_format,
2957            column_formats,
2958        })
2959        .await?;
2960
2961        // In Postgres, binary copy has a header that is followed (in the same
2962        // CopyData) by the first row. In order to replicate their behavior, use a
2963        // common vec that we can extend one time now and then fill up with the encode
2964        // functions.
2965        let mut out = Vec::new();
2966
2967        if let CopyFormat::Binary = format {
2968            // 11-byte signature.
2969            out.extend(b"PGCOPY\n\xFF\r\n\0");
2970            // 32-bit flags field.
2971            out.extend([0, 0, 0, 0]);
2972            // 32-bit header extension length field.
2973            out.extend([0, 0, 0, 0]);
2974        }
2975
2976        let mut count = 0;
2977        let mut total_sent_bytes = 0;
2978        loop {
2979            tokio::select! {
2980                e = self.conn.wait_closed() => return Err(e),
2981                batch = stream.recv() => match batch {
2982                    None => break,
2983                    Some(PeekResponseUnary::Error(err)) => {
2984                        let text = err.to_string();
2985                        return self
2986                            .send_error_and_get_state(err.into_response(Severity::Error))
2987                            .await
2988                            .map(|state| (state, SendRowsEndedReason::Errored { error: text }));
2989                    }
2990                    Some(PeekResponseUnary::DependencyDropped(dep)) => {
2991                        let err = dep.to_concurrent_dependency_drop();
2992                        let text = err.to_string();
2993                        let resp = err.into_response(Severity::Error);
2994                        return self
2995                            .send_error_and_get_state(resp)
2996                            .await
2997                            .map(|state| (state, SendRowsEndedReason::Errored { error: text }));
2998                    }
2999                    Some(PeekResponseUnary::Canceled) => {
3000                        return self.send_error_and_get_state(ErrorResponse::error(
3001                                SqlState::QUERY_CANCELED,
3002                                "canceling statement due to user request",
3003                            ))
3004                            .await.map(|state| (state, SendRowsEndedReason::Canceled));
3005                    }
3006                    Some(PeekResponseUnary::Rows(mut rows)) => {
3007                        count += rows.count();
3008                        while let Some(row) = rows.next() {
3009                            total_sent_bytes += row.byte_len();
3010                            encode_fn(row, typ, &mut out)?;
3011                            self.send(BackendMessage::CopyData(mem::take(&mut out)))
3012                                .await?;
3013                        }
3014                    }
3015                },
3016                notice = self.adapter_client.session().recv_notice() => {
3017                    self.send(notice.into_response())
3018                        .await?;
3019                    self.conn.flush().await?;
3020                }
3021            }
3022
3023            self.conn.flush().await?;
3024        }
3025        // Send required trailers.
3026        if let CopyFormat::Binary = format {
3027            let trailer: i16 = -1;
3028            out.extend(trailer.to_be_bytes());
3029            self.send(BackendMessage::CopyData(mem::take(&mut out)))
3030                .await?;
3031        }
3032
3033        let tag = format!("COPY {}", count);
3034        self.send(BackendMessage::CopyDone).await?;
3035        let state = match self.settle_statement(ends_simple_query).await {
3036            Some(err) => self.send_error_and_get_state(err).await?,
3037            None => {
3038                self.send(BackendMessage::CommandComplete { tag }).await?;
3039                State::Ready
3040            }
3041        };
3042        Ok((
3043            state,
3044            SendRowsEndedReason::Success {
3045                result_size: u64::cast_from(total_sent_bytes),
3046                rows_returned: u64::cast_from(count),
3047            },
3048        ))
3049    }
3050
3051    /// Handles the copy-in mode of the postgres protocol from transferring
3052    /// data to the server.
3053    #[instrument(level = "debug")]
3054    async fn copy_from(
3055        &mut self,
3056        target_id: CatalogItemId,
3057        target_name: String,
3058        columns: Vec<ColumnIndex>,
3059        params: CopyFormatParams<'static>,
3060        row_desc: RelationDesc,
3061        mut ctx_extra: ExecuteContextGuard,
3062        ends_simple_query: bool,
3063    ) -> Result<State, io::Error> {
3064        let res = self
3065            .copy_from_inner(
3066                target_id,
3067                target_name,
3068                columns,
3069                params,
3070                row_desc,
3071                &mut ctx_extra,
3072                ends_simple_query,
3073            )
3074            .await;
3075        match &res {
3076            Ok(State::Ready) => {
3077                self.adapter_client.retire_execute(
3078                    ctx_extra,
3079                    StatementEndedExecutionReason::Success {
3080                        result_size: None,
3081                        rows_returned: None,
3082                        execution_strategy: None,
3083                    },
3084                );
3085            }
3086            Ok(State::Done) => {
3087                // The connection closed gracefully without sending us a `CopyDone`,
3088                // causing us to just drop the copy request.
3089                // For the purposes of statement logging, we count this as a cancellation.
3090                self.adapter_client
3091                    .retire_execute(ctx_extra, StatementEndedExecutionReason::Canceled);
3092            }
3093            Err(e) => {
3094                self.adapter_client.retire_execute(
3095                    ctx_extra,
3096                    StatementEndedExecutionReason::Errored {
3097                        error: format!("{e}"),
3098                    },
3099                );
3100            }
3101            Ok(State::Drain) => {}
3102        }
3103        res
3104    }
3105
3106    async fn copy_from_inner(
3107        &mut self,
3108        target_id: CatalogItemId,
3109        target_name: String,
3110        columns: Vec<ColumnIndex>,
3111        params: CopyFormatParams<'static>,
3112        row_desc: RelationDesc,
3113        ctx_extra: &mut ExecuteContextGuard,
3114        ends_simple_query: bool,
3115    ) -> Result<State, io::Error> {
3116        let typ = row_desc.typ();
3117        let column_formats = vec![Format::Text; typ.column_types.len()];
3118        self.send(BackendMessage::CopyInResponse {
3119            overall_format: Format::Text,
3120            column_formats,
3121        })
3122        .await?;
3123        self.conn.flush().await?;
3124
3125        // Set up the parallel streaming batch builders in the coordinator.
3126        let writer = match self
3127            .adapter_client
3128            .start_copy_from_stdin(
3129                target_id,
3130                target_name.clone(),
3131                columns.clone(),
3132                row_desc.clone(),
3133                params.clone(),
3134            )
3135            .await
3136        {
3137            Ok(writer) => writer,
3138            Err(e) => {
3139                // Drain remaining CopyData/CopyDone/CopyFail messages from the
3140                // socket. Since CopyInResponse was already sent, the client may
3141                // have pipelined copy data that we must consume before returning
3142                // the error, otherwise they'd be misinterpreted as top-level
3143                // protocol messages and cause a deadlock.
3144                loop {
3145                    match self.conn.recv().await? {
3146                        Some(FrontendMessage::CopyData(_)) => {}
3147                        Some(FrontendMessage::CopyDone) | Some(FrontendMessage::CopyFail(_)) => {
3148                            break;
3149                        }
3150                        Some(FrontendMessage::Flush) | Some(FrontendMessage::Sync) => {}
3151                        Some(_) => break,
3152                        None => return Ok(State::Done),
3153                    }
3154                }
3155                self.adapter_client.retire_execute(
3156                    std::mem::take(ctx_extra),
3157                    StatementEndedExecutionReason::Errored {
3158                        error: e.to_string(),
3159                    },
3160                );
3161                return self
3162                    .send_error_and_get_state(e.into_response(Severity::Error))
3163                    .await;
3164            }
3165        };
3166
3167        // Batch size for splitting raw data across parallel workers (~32MB).
3168        const BATCH_SIZE: usize = 32 * 1024 * 1024;
3169        let max_copy_from_row_size = self
3170            .adapter_client
3171            .get_system_vars()
3172            .await
3173            .max_copy_from_row_size()
3174            .try_into()
3175            .unwrap_or(usize::MAX);
3176
3177        let mut data = Vec::new();
3178        let mut row_scanner = CopyRowScanner::new(&params, row_desc.arity());
3179        let num_workers = writer.batch_txs.len();
3180        let mut next_worker: usize = 0;
3181        let mut saw_copy_done = false;
3182        let mut saw_end_marker = false;
3183        let mut copy_from_error: Option<(SqlState, String)> = None;
3184
3185        // Receive loop: accumulate CopyData, split at row boundaries,
3186        // round-robin raw chunks to parallel batch builder workers.
3187        loop {
3188            let message = self.conn.recv().await?;
3189            match message {
3190                Some(FrontendMessage::CopyData(buf)) => {
3191                    if saw_end_marker {
3192                        // Per PostgreSQL COPY behavior, ignore all bytes after
3193                        // the end-of-copy marker until CopyDone.
3194                        continue;
3195                    }
3196                    data.extend(buf);
3197                    row_scanner.scan_new_bytes(&mut data);
3198
3199                    if let Some(end_pos) = row_scanner.end_marker_end() {
3200                        data.truncate(end_pos);
3201                        row_scanner.on_truncate(end_pos);
3202                        saw_end_marker = true;
3203                    }
3204
3205                    // Guard against pathological single rows that never terminate.
3206                    if row_scanner.current_row_size(data.len()) > max_copy_from_row_size {
3207                        copy_from_error = Some((
3208                            SqlState::INSUFFICIENT_RESOURCES,
3209                            format!(
3210                                "COPY FROM STDIN row exceeded max_copy_from_row_size \
3211                                 ({max_copy_from_row_size} bytes)"
3212                            ),
3213                        ));
3214                        break;
3215                    }
3216
3217                    let mut send_failed = false;
3218                    // NOTE: A batch that reached the cap on blank records is
3219                    // copied out. Splitting it off would move the rest of the
3220                    // buffer once per batch, and leave each batch with the
3221                    // capacity of the whole buffer.
3222                    let mut sent = 0;
3223                    for end in row_scanner.take_batch_ends() {
3224                        let chunk = data[sent..end].to_vec();
3225                        sent = end;
3226                        if writer.batch_txs[next_worker].send(chunk).await.is_err() {
3227                            send_failed = true;
3228                            break;
3229                        }
3230                        next_worker = (next_worker + 1) % num_workers;
3231                    }
3232                    data.drain(..sent);
3233                    row_scanner.on_split(sent);
3234
3235                    // When buffer exceeds batch size, split at the last complete row
3236                    // and send the complete rows chunk to the next worker.
3237                    while data.len() >= BATCH_SIZE {
3238                        let split_pos = match row_scanner.last_row_end() {
3239                            Some(pos) => pos,
3240                            None => break, // no complete row yet
3241                        };
3242                        let remainder = data.split_off(split_pos);
3243                        let chunk = std::mem::replace(&mut data, remainder);
3244                        row_scanner.on_split(split_pos);
3245                        if writer.batch_txs[next_worker].send(chunk).await.is_err() {
3246                            send_failed = true;
3247                            break;
3248                        }
3249                        next_worker = (next_worker + 1) % num_workers;
3250                    }
3251                    // Worker dropped (likely errored) — stop sending,
3252                    // fall through to completion_rx for the real error.
3253                    if send_failed {
3254                        break;
3255                    }
3256                }
3257                Some(FrontendMessage::CopyDone) => {
3258                    // Send any remaining data to the next worker.
3259                    if !data.is_empty() {
3260                        let chunk = std::mem::take(&mut data);
3261                        // Ignore send failure — completion_rx will have the error.
3262                        let _ = writer.batch_txs[next_worker].send(chunk).await;
3263                    }
3264                    saw_copy_done = true;
3265                    break;
3266                }
3267                Some(FrontendMessage::CopyFail(err)) => {
3268                    self.adapter_client.retire_execute(
3269                        std::mem::take(ctx_extra),
3270                        StatementEndedExecutionReason::Canceled,
3271                    );
3272                    // Drop the writer to signal cancellation to the background tasks.
3273                    drop(writer);
3274                    return self
3275                        .send_error_and_get_state(ErrorResponse::error(
3276                            SqlState::QUERY_CANCELED,
3277                            format!("COPY from stdin failed: {}", err),
3278                        ))
3279                        .await;
3280                }
3281                Some(FrontendMessage::Flush) | Some(FrontendMessage::Sync) => {}
3282                Some(_) => {
3283                    let msg = "unexpected message type during COPY from stdin";
3284                    self.adapter_client.retire_execute(
3285                        std::mem::take(ctx_extra),
3286                        StatementEndedExecutionReason::Errored {
3287                            error: msg.to_string(),
3288                        },
3289                    );
3290                    drop(writer);
3291                    return self
3292                        .send_error_and_get_state(ErrorResponse::error(
3293                            SqlState::PROTOCOL_VIOLATION,
3294                            msg,
3295                        ))
3296                        .await;
3297                }
3298                None => {
3299                    drop(writer);
3300                    return Ok(State::Done);
3301                }
3302            }
3303        }
3304
3305        // If we exited the receive loop before seeing `CopyDone` (e.g. because
3306        // a worker failed and dropped its channel), keep draining COPY input to
3307        // avoid desynchronizing the protocol state machine.
3308        if !saw_copy_done {
3309            loop {
3310                match self.conn.recv().await? {
3311                    Some(FrontendMessage::CopyData(_)) => {}
3312                    Some(FrontendMessage::CopyDone) | Some(FrontendMessage::CopyFail(_)) => {
3313                        break;
3314                    }
3315                    Some(FrontendMessage::Flush) | Some(FrontendMessage::Sync) => {}
3316                    Some(_) => {
3317                        let msg = "unexpected message type during COPY from stdin";
3318                        self.adapter_client.retire_execute(
3319                            std::mem::take(ctx_extra),
3320                            StatementEndedExecutionReason::Errored {
3321                                error: msg.to_string(),
3322                            },
3323                        );
3324                        drop(writer);
3325                        return self
3326                            .send_error_and_get_state(ErrorResponse::error(
3327                                SqlState::PROTOCOL_VIOLATION,
3328                                msg,
3329                            ))
3330                            .await;
3331                    }
3332                    None => {
3333                        drop(writer);
3334                        return Ok(State::Done);
3335                    }
3336                }
3337            }
3338        }
3339
3340        if let Some((code, msg)) = copy_from_error {
3341            self.adapter_client.retire_execute(
3342                std::mem::take(ctx_extra),
3343                StatementEndedExecutionReason::Errored { error: msg.clone() },
3344            );
3345            drop(writer);
3346            return self
3347                .send_error_and_get_state(ErrorResponse::error(code, msg))
3348                .await;
3349        }
3350
3351        // Drop all senders to signal EOF to the background batch builders.
3352        // If copy_err is set, a worker already failed — dropping the senders
3353        // will cause remaining workers to stop, and we'll get the real error
3354        // from completion_rx below.
3355        drop(writer.batch_txs);
3356
3357        // Wait for all parallel workers to finish building batches.
3358        let (proto_batches, row_count) = match writer.completion_rx.await {
3359            Ok(Ok(result)) => result,
3360            Ok(Err(e)) => {
3361                self.adapter_client.retire_execute(
3362                    std::mem::take(ctx_extra),
3363                    StatementEndedExecutionReason::Errored {
3364                        error: e.to_string(),
3365                    },
3366                );
3367                return self
3368                    .send_error_and_get_state(e.into_response(Severity::Error))
3369                    .await;
3370            }
3371            Err(_) => {
3372                let msg = "COPY FROM STDIN: background batch builder tasks dropped";
3373                self.adapter_client.retire_execute(
3374                    std::mem::take(ctx_extra),
3375                    StatementEndedExecutionReason::Errored {
3376                        error: msg.to_string(),
3377                    },
3378                );
3379                return self
3380                    .send_error_and_get_state(ErrorResponse::error(SqlState::INTERNAL_ERROR, msg))
3381                    .await;
3382            }
3383        };
3384
3385        // Stage all batches in the session's transaction for atomic commit.
3386        if let Err(e) = self
3387            .adapter_client
3388            .stage_copy_from_stdin_batches(target_id, proto_batches)
3389        {
3390            self.adapter_client.retire_execute(
3391                std::mem::take(ctx_extra),
3392                StatementEndedExecutionReason::Errored {
3393                    error: e.to_string(),
3394                },
3395            );
3396            return self
3397                .send_error_and_get_state(e.into_response(Severity::Error))
3398                .await;
3399        }
3400
3401        if let Some(err) = self.settle_statement(ends_simple_query).await {
3402            self.adapter_client.retire_execute(
3403                std::mem::take(ctx_extra),
3404                StatementEndedExecutionReason::Errored {
3405                    error: err.message.clone(),
3406                },
3407            );
3408            return self.send_error_and_get_state(err).await;
3409        }
3410        let tag = format!("COPY {}", row_count);
3411        self.send(BackendMessage::CommandComplete { tag }).await?;
3412
3413        Ok(State::Ready)
3414    }
3415
3416    #[instrument(level = "debug")]
3417    async fn send_pending_notices(&mut self) -> Result<(), io::Error> {
3418        let notices = self
3419            .adapter_client
3420            .session()
3421            .drain_notices()
3422            .into_iter()
3423            .map(|notice| BackendMessage::ErrorResponse(notice.into_response()));
3424        self.send_all(notices).await?;
3425        Ok(())
3426    }
3427
3428    #[instrument(level = "debug")]
3429    async fn send_error_and_get_state(&mut self, err: ErrorResponse) -> Result<State, io::Error> {
3430        assert!(err.severity.is_error());
3431        debug!(
3432            "cid={} error code={}",
3433            self.adapter_client.session().conn_id(),
3434            err.code.code()
3435        );
3436        let is_fatal = err.severity.is_fatal();
3437        self.send(BackendMessage::ErrorResponse(err)).await?;
3438
3439        let txn = self.adapter_client.session().transaction();
3440        match txn {
3441            // Error can be called from describe and parse and so might not be in an active
3442            // transaction.
3443            TransactionStatus::Default | TransactionStatus::Failed(_) => {}
3444            // In Started (i.e., a single statement), cleanup ourselves.
3445            TransactionStatus::Started(_) => {
3446                self.rollback_transaction().await?;
3447            }
3448            // Implicit transactions also clear themselves.
3449            TransactionStatus::InTransactionImplicit(_) => {
3450                self.rollback_transaction().await?;
3451            }
3452            // Explicit transactions move to failed.
3453            TransactionStatus::InTransaction(_) => {
3454                self.adapter_client.fail_transaction();
3455            }
3456        };
3457        if is_fatal {
3458            Ok(State::Done)
3459        } else {
3460            Ok(State::Drain)
3461        }
3462    }
3463
3464    #[instrument(level = "debug")]
3465    async fn aborted_txn_error(&mut self) -> Result<State, io::Error> {
3466        self.send(BackendMessage::ErrorResponse(ErrorResponse::error(
3467            SqlState::IN_FAILED_SQL_TRANSACTION,
3468            ABORTED_TXN_MSG,
3469        )))
3470        .await?;
3471        Ok(State::Drain)
3472    }
3473
3474    fn is_aborted_txn(&mut self) -> bool {
3475        matches!(
3476            self.adapter_client.session().transaction(),
3477            TransactionStatus::Failed(_)
3478        )
3479    }
3480}
3481
3482fn pad_formats(formats: Vec<Format>, n: usize) -> Result<Vec<Format>, String> {
3483    match (formats.len(), n) {
3484        (0, e) => Ok(vec![Format::Text; e]),
3485        (1, e) => Ok(iter::repeat(formats[0]).take(e).collect()),
3486        (a, e) if a == e => Ok(formats),
3487        (a, e) => Err(format!(
3488            "expected {} field format specifiers, but got {}",
3489            e, a
3490        )),
3491    }
3492}
3493
3494fn describe_rows(stmt_desc: &StatementDesc, formats: &[Format]) -> BackendMessage {
3495    match &stmt_desc.relation_desc {
3496        Some(desc) if !stmt_desc.is_copy => {
3497            BackendMessage::RowDescription(message::encode_row_description(desc, formats))
3498        }
3499        _ => BackendMessage::NoData,
3500    }
3501}
3502
3503type GetResponse = fn(
3504    max_rows: ExecuteCount,
3505    total_sent_rows: usize,
3506    fetch_portal: Option<PortalRefMut>,
3507) -> BackendMessage;
3508
3509// A GetResponse used by send_rows during execute messages on portals or for
3510// simple query messages.
3511fn portal_exec_message(
3512    max_rows: ExecuteCount,
3513    total_sent_rows: usize,
3514    _fetch_portal: Option<PortalRefMut>,
3515) -> BackendMessage {
3516    // If max_rows is not specified, we will always send back a CommandComplete. If
3517    // max_rows is specified, we only send CommandComplete if there were more rows
3518    // requested than were remaining. That is, if max_rows == number of rows that
3519    // were remaining before sending (not that are remaining after sending), then
3520    // we still send a PortalSuspended. The number of remaining rows after the rows
3521    // have been sent doesn't matter. This matches postgres.
3522    match max_rows {
3523        ExecuteCount::Count(max_rows) if max_rows <= total_sent_rows => {
3524            BackendMessage::PortalSuspended
3525        }
3526        _ => BackendMessage::CommandComplete {
3527            tag: format!("SELECT {}", total_sent_rows),
3528        },
3529    }
3530}
3531
3532// A GetResponse used by send_rows during FETCH queries.
3533fn fetch_message(
3534    _max_rows: ExecuteCount,
3535    total_sent_rows: usize,
3536    fetch_portal: Option<PortalRefMut>,
3537) -> BackendMessage {
3538    let tag = format!("FETCH {}", total_sent_rows);
3539    if let Some(portal) = fetch_portal {
3540        *portal.state = PortalState::Completed(Some(tag.clone()));
3541    }
3542    BackendMessage::CommandComplete { tag }
3543}
3544
3545fn get_authenticator(
3546    authenticator_kind: listeners::AuthenticatorKind,
3547    frontegg: Option<FronteggAuthenticator>,
3548    oidc: GenericOidcAuthenticator,
3549    adapter_client: mz_adapter::Client,
3550) -> Authenticator {
3551    match authenticator_kind {
3552        listeners::AuthenticatorKind::Frontegg => Authenticator::Frontegg(frontegg.expect(
3553            "Frontegg authenticator should exist with listeners::AuthenticatorKind::Frontegg",
3554        )),
3555        listeners::AuthenticatorKind::Password => Authenticator::Password(adapter_client),
3556        listeners::AuthenticatorKind::Sasl => Authenticator::Sasl(adapter_client),
3557        listeners::AuthenticatorKind::Oidc => Authenticator::Oidc(oidc),
3558        listeners::AuthenticatorKind::None => Authenticator::None,
3559    }
3560}
3561
3562#[derive(Debug, Copy, Clone)]
3563enum ExecuteCount {
3564    All,
3565    Count(usize),
3566}
3567
3568// See postgres' backend/tcop/postgres.c IsTransactionExitStmt.
3569fn is_txn_exit_stmt(stmt: Option<&Statement<Raw>>) -> bool {
3570    match stmt {
3571        // Add PREPARE to this if we ever support it.
3572        Some(stmt) => matches!(stmt, Statement::Commit(_) | Statement::Rollback(_)),
3573        None => false,
3574    }
3575}
3576
3577#[derive(Debug)]
3578enum FetchResult {
3579    Rows(Option<Box<dyn RowIterator + Send + Sync>>),
3580    FlushRows,
3581    Canceled,
3582    Error(ErrorResponse),
3583    Notice(AdapterNotice),
3584}
3585
3586/// Cap on the blank lines that are records in one batch of CSV data.
3587///
3588/// NOTE: A worker decodes a batch into rows before it writes any of them, and a
3589/// blank line is a `Row` from one byte of input. Without the cap, a batch of
3590/// blank lines would decode into `size_of::<Row>()` times its size.
3591const MAX_BLANK_RECORDS_PER_BATCH: usize = 1 << 20;
3592
3593#[derive(Debug)]
3594struct CopyRowScanner {
3595    scan_pos: usize,
3596    last_row_end: Option<usize>,
3597    end_marker_end: Option<usize>,
3598    // Start of the current CSV record, including any bytes read in prior messages.
3599    record_start: usize,
3600    csv: Option<CsvScanState>,
3601}
3602
3603#[derive(Debug)]
3604struct CsvScanState {
3605    reader: csv_core::Reader,
3606    output: Vec<u8>,
3607    ends: Vec<usize>,
3608    pending_cr: bool,
3609    at_stream_start: bool,
3610    skip_first_record: bool,
3611    blank_line_is_record: bool,
3612    // Blank lines that are records since the last of `batch_ends`.
3613    blank_records: usize,
3614    // Row ends at which a batch reached `MAX_BLANK_RECORDS_PER_BATCH`.
3615    batch_ends: Vec<usize>,
3616}
3617
3618impl CopyRowScanner {
3619    fn new(params: &CopyFormatParams<'_>, column_count: usize) -> Self {
3620        let csv = match params {
3621            CopyFormatParams::Csv(params) => Some(CsvScanState {
3622                reader: params.reader(),
3623                // NOTE: csv-core's `read_record` returns once `output` or `ends`
3624                // is full, so their lengths bound how much input one call can
3625                // scan. The scanner never reads their contents.
3626                output: vec![0; 64 * 1024],
3627                ends: vec![0; 1024],
3628                pending_cr: false,
3629                at_stream_start: true,
3630                skip_first_record: params.header,
3631                blank_line_is_record: csv_blank_line_is_record(column_count),
3632                blank_records: 0,
3633                batch_ends: Vec::new(),
3634            }),
3635            _ => None,
3636        };
3637
3638        CopyRowScanner {
3639            scan_pos: 0,
3640            last_row_end: None,
3641            end_marker_end: None,
3642            record_start: 0,
3643            csv,
3644        }
3645    }
3646
3647    fn scan_new_bytes(&mut self, data: &mut Vec<u8>) {
3648        if self.scan_pos >= data.len() {
3649            return;
3650        }
3651
3652        if let Some(csv) = self.csv.as_mut() {
3653            if csv.at_stream_start {
3654                const BOM: &[u8] = b"\xef\xbb\xbf";
3655                if data.len() < BOM.len() && BOM.starts_with(data) {
3656                    return;
3657                }
3658                if data.starts_with(BOM) {
3659                    data.drain(..BOM.len());
3660                }
3661                csv.at_stream_start = false;
3662            }
3663            let mut pos = self.scan_pos;
3664            while pos < data.len() {
3665                if csv.pending_cr {
3666                    // A split between CR and LF would turn the LF into another record.
3667                    pos += usize::from(data[pos] == b'\n');
3668                    csv.pending_cr = false;
3669                    self.last_row_end = Some(pos);
3670                    self.record_start = pos;
3671                    continue;
3672                }
3673                if csv.blank_records >= MAX_BLANK_RECORDS_PER_BATCH {
3674                    // NOTE: `pos` is a row end here. A check where the count
3675                    // grows would end a batch at a CR whose LF is still to come.
3676                    csv.batch_ends.push(pos);
3677                    csv.blank_records = 0;
3678                }
3679                let blank_record = csv.blank_line_is_record
3680                    && pos == self.record_start
3681                    && matches!(data[pos], b'\r' | b'\n');
3682                if blank_record {
3683                    csv.blank_records += 1;
3684                    pos += 1;
3685                } else {
3686                    let (result, n, _, _) =
3687                        csv.reader
3688                            .read_record(&data[pos..], &mut csv.output, &mut csv.ends);
3689                    pos += n;
3690                    match result {
3691                        ReadRecordResult::Record => {}
3692                        ReadRecordResult::OutputFull | ReadRecordResult::OutputEndsFull => continue,
3693                        ReadRecordResult::End | ReadRecordResult::InputEmpty => break,
3694                    }
3695                }
3696                // Where blank lines are not records, csv-core skips them as
3697                // part of the record that follows.
3698                let record = &data[self.record_start..pos - 1];
3699                let skipped = record
3700                    .iter()
3701                    .take_while(|b| matches!(b, b'\r' | b'\n'))
3702                    .count();
3703                let is_marker = !csv.skip_first_record && &record[skipped..] == b"\\.";
3704                csv.skip_first_record = false;
3705                csv.pending_cr = data[pos - 1] == b'\r' && !is_marker;
3706                if !csv.pending_cr {
3707                    self.last_row_end = Some(pos);
3708                }
3709                self.record_start = pos;
3710                if is_marker {
3711                    self.end_marker_end = Some(pos);
3712                    break;
3713                }
3714            }
3715        } else {
3716            let mut row_start = self.last_row_end.unwrap_or(0);
3717            for (offset, b) in data[self.scan_pos..].iter().enumerate() {
3718                if *b == b'\n' {
3719                    let row_end = self.scan_pos + offset + 1;
3720                    self.last_row_end = Some(row_end);
3721                    if self.end_marker_end.is_none() {
3722                        let row = &data[row_start..row_end];
3723                        if row.get(0..2) == Some(b"\\.") {
3724                            self.end_marker_end = Some(row_end);
3725                            break;
3726                        }
3727                    }
3728                    row_start = row_end;
3729                }
3730            }
3731        }
3732
3733        self.scan_pos = data.len();
3734    }
3735
3736    fn last_row_end(&self) -> Option<usize> {
3737        self.last_row_end
3738    }
3739
3740    fn end_marker_end(&self) -> Option<usize> {
3741        self.end_marker_end
3742    }
3743
3744    fn take_batch_ends(&mut self) -> Vec<usize> {
3745        match &mut self.csv {
3746            Some(csv) => std::mem::take(&mut csv.batch_ends),
3747            None => Vec::new(),
3748        }
3749    }
3750
3751    fn current_row_size(&self, data_len: usize) -> usize {
3752        // A CSV record that ends in `\r` is complete at `record_start` before
3753        // it becomes splittable at `last_row_end`.
3754        let row_start = self.last_row_end.unwrap_or(0).max(self.record_start);
3755        data_len.saturating_sub(row_start)
3756    }
3757
3758    fn on_split(&mut self, split_pos: usize) {
3759        self.scan_pos = self.scan_pos.saturating_sub(split_pos);
3760        // A split ahead of the last row end keeps that row end.
3761        self.last_row_end = self
3762            .last_row_end
3763            .and_then(|end| end.checked_sub(split_pos))
3764            .filter(|&end| end > 0);
3765        self.end_marker_end = self
3766            .end_marker_end
3767            .and_then(|end| end.checked_sub(split_pos));
3768        soft_assert_or_log!(
3769            self.csv.is_none() || self.record_start >= split_pos,
3770            "split bisected an in-progress CSV record: record_start={} < split_pos={}",
3771            self.record_start,
3772            split_pos,
3773        );
3774        self.record_start = self.record_start.saturating_sub(split_pos);
3775    }
3776
3777    fn on_truncate(&mut self, new_len: usize) {
3778        self.scan_pos = self.scan_pos.min(new_len);
3779        self.last_row_end = self.last_row_end.filter(|&end| end <= new_len);
3780        self.end_marker_end = self.end_marker_end.filter(|&end| end <= new_len);
3781        self.record_start = self.record_start.min(new_len);
3782    }
3783}
3784
3785#[cfg(test)]
3786mod test {
3787    use super::*;
3788
3789    #[mz_ore::test]
3790    fn test_copy_row_scanner_csv_boundaries() {
3791        let format = CopyFormatParams::Csv(CopyCsvFormatParams {
3792            header: true,
3793            ..Default::default()
3794        });
3795        for (input, row_end, marker, partial) in [
3796            ("\n\n\r\n\r", 4, None, 0),
3797            ("a\rb\r\nc", 5, None, 1),
3798            ("h\ra\r", 2, None, 0),
3799            ("\u{feff}\n\\.\nignored", 4, Some(4), 0),
3800            ("\n\\.\nignored", 4, Some(4), 0),
3801            ("h\r\\.\rignored", 5, Some(5), 0),
3802            ("h\r\n\"\\.\"\r\n\\.\r\nignored", 12, Some(12), 0),
3803            ("\n\"a\n\\.\nb\"\n", 10, None, 0),
3804        ] {
3805            for split in 0..=input.len() {
3806                let mut scanner = CopyRowScanner::new(&format, 1);
3807                let mut data = input.as_bytes()[..split].to_vec();
3808                scanner.scan_new_bytes(&mut data);
3809                if scanner.end_marker_end().is_none() {
3810                    data.extend_from_slice(&input.as_bytes()[split..]);
3811                    scanner.scan_new_bytes(&mut data);
3812                }
3813                assert_eq!(
3814                    scanner.end_marker_end(),
3815                    marker,
3816                    "{input:?} split at {split}"
3817                );
3818                if let Some(end) = marker {
3819                    data.truncate(end);
3820                    scanner.on_truncate(end);
3821                }
3822                assert_eq!(
3823                    scanner.last_row_end(),
3824                    Some(row_end),
3825                    "{input:?} split at {split}"
3826                );
3827                assert_eq!(scanner.current_row_size(data.len()), partial);
3828                scanner.on_split(row_end);
3829            }
3830        }
3831    }
3832
3833    #[mz_ore::test]
3834    fn test_copy_row_scanner_csv_skipped_blank_lines() {
3835        let format = CopyFormatParams::Csv(CopyCsvFormatParams {
3836            header: true,
3837            ..Default::default()
3838        });
3839        for (input, row_end, marker, partial) in [
3840            // The blank line is skipped, so `\.` is the header.
3841            ("\n\\.\na,b\n", Some(8), None, 0),
3842            // No chunk ends ahead of the header, and the lines count as its size.
3843            ("\n\r\n", None, None, 3),
3844            ("\nh,h\n\r\n\\.\nignored", Some(10), Some(10), 0),
3845        ] {
3846            for split in 0..=input.len() {
3847                let mut scanner = CopyRowScanner::new(&format, 2);
3848                let mut data = input.as_bytes()[..split].to_vec();
3849                scanner.scan_new_bytes(&mut data);
3850                if scanner.end_marker_end().is_none() {
3851                    data.extend_from_slice(&input.as_bytes()[split..]);
3852                    scanner.scan_new_bytes(&mut data);
3853                }
3854                assert_eq!(
3855                    scanner.end_marker_end(),
3856                    marker,
3857                    "{input:?} split at {split}"
3858                );
3859                if let Some(end) = marker {
3860                    data.truncate(end);
3861                    scanner.on_truncate(end);
3862                }
3863                assert_eq!(
3864                    scanner.last_row_end(),
3865                    row_end,
3866                    "{input:?} split at {split}"
3867                );
3868                assert_eq!(
3869                    scanner.current_row_size(data.len()),
3870                    partial,
3871                    "{input:?} split at {split}"
3872                );
3873            }
3874        }
3875    }
3876
3877    #[mz_ore::test]
3878    fn test_copy_row_scanner_csv_blank_record_cap() {
3879        let params = CopyFormatParams::Csv(CopyCsvFormatParams::default());
3880        let cap = MAX_BLANK_RECORDS_PER_BATCH;
3881
3882        // With several columns the lines are skipped, and need no cap.
3883        let mut scanner = CopyRowScanner::new(&params, 2);
3884        scanner.scan_new_bytes(&mut vec![b'\n'; 2 * cap + 1]);
3885        assert!(scanner.take_batch_ends().is_empty());
3886
3887        let mut scanner = CopyRowScanner::new(&params, 1);
3888        let mut data = vec![b'\n'; 2 * cap + 1];
3889        scanner.scan_new_bytes(&mut data);
3890        assert_eq!(scanner.take_batch_ends(), [cap, 2 * cap]);
3891        scanner.on_split(2 * cap);
3892        assert_eq!(scanner.last_row_end(), Some(1));
3893
3894        // The last blank line of a batch ends in a CR, and its LF is in the
3895        // next message.
3896        let mut scanner = CopyRowScanner::new(&params, 1);
3897        let mut data = b"\r\n".repeat(cap - 1);
3898        data.push(b'\r');
3899        scanner.scan_new_bytes(&mut data);
3900        assert!(scanner.take_batch_ends().is_empty());
3901        data.extend_from_slice(b"\n\r\n");
3902        scanner.scan_new_bytes(&mut data);
3903        assert_eq!(scanner.take_batch_ends(), [2 * cap]);
3904    }
3905
3906    #[mz_ore::test]
3907    fn test_copy_row_scanner_csv_row_larger_than_scan_buffers() {
3908        let params = CopyFormatParams::Csv(CopyCsvFormatParams::default());
3909        let long_field = "x".repeat(200_000);
3910        let many_fields = vec!["x"; 3_000].join(",");
3911        for row in [long_field, many_fields] {
3912            let mut scanner = CopyRowScanner::new(&params, 1);
3913            let mut data = format!("{row}\n{row}").into_bytes();
3914            scanner.scan_new_bytes(&mut data);
3915            assert_eq!(scanner.last_row_end(), Some(row.len() + 1));
3916        }
3917    }
3918
3919    #[mz_ore::test]
3920    fn test_copy_row_scanner_non_csv_split() {
3921        // Regression: `record_start` is only maintained for the CSV path; the
3922        // text and binary paths leave it at 0. `on_split` must therefore not
3923        // assert `record_start >= split_pos` for those formats — that fires on
3924        // every split of a large text/binary COPY stream (soft-assertions
3925        // panic under test). Mirrors `COPY ... FROM STDIN` (default text
3926        // format) splitting at a row boundary once the buffer fills.
3927        for params in [
3928            CopyFormatParams::Text(CopyTextFormatParams::default()),
3929            CopyFormatParams::Binary,
3930        ] {
3931            let mut scanner = CopyRowScanner::new(&params, 4);
3932            let data = b"1\thello world\t2\tsome text value here\n\
3933                         3\thello world\t6\tsome text value here\n";
3934            scanner.scan_new_bytes(&mut data.to_vec());
3935            let split_pos = scanner.last_row_end().expect("a complete row");
3936            assert!(split_pos > 0, "params={params:?}");
3937            // Must not panic via the CSV-only `on_split` soft-assert.
3938            scanner.on_split(split_pos);
3939            assert_eq!(scanner.record_start, 0, "params={params:?}");
3940        }
3941    }
3942
3943    #[mz_ore::test]
3944    fn test_parse_options() {
3945        struct TestCase {
3946            input: &'static str,
3947            expect: Result<Vec<(&'static str, &'static str)>, ()>,
3948        }
3949        let tests = vec![
3950            TestCase {
3951                input: "",
3952                expect: Ok(vec![]),
3953            },
3954            TestCase {
3955                input: "--key",
3956                expect: Err(()),
3957            },
3958            TestCase {
3959                input: "--key=val",
3960                expect: Ok(vec![("key", "val")]),
3961            },
3962            TestCase {
3963                input: r#"--key=val -ckey2=val2 -c key3=val3 -c key4=val4 -ckey5=val5"#,
3964                expect: Ok(vec![
3965                    ("key", "val"),
3966                    ("key2", "val2"),
3967                    ("key3", "val3"),
3968                    ("key4", "val4"),
3969                    ("key5", "val5"),
3970                ]),
3971            },
3972            TestCase {
3973                input: r#"-c\ key=val"#,
3974                expect: Ok(vec![(" key", "val")]),
3975            },
3976            TestCase {
3977                input: "--key=val -ckey2 val2",
3978                expect: Err(()),
3979            },
3980            // Unclear what this should do.
3981            TestCase {
3982                input: "--key=",
3983                expect: Ok(vec![("key", "")]),
3984            },
3985        ];
3986        for test in tests {
3987            let got = parse_options(test.input);
3988            let expect = test.expect.map(|r| {
3989                r.into_iter()
3990                    .map(|(k, v)| (k.to_owned(), v.to_owned()))
3991                    .collect()
3992            });
3993            assert_eq!(got, expect, "input: {}", test.input);
3994        }
3995    }
3996
3997    #[mz_ore::test]
3998    fn test_parse_option() {
3999        struct TestCase {
4000            input: &'static str,
4001            expect: Result<(&'static str, &'static str), ()>,
4002        }
4003        let tests = vec![
4004            TestCase {
4005                input: "",
4006                expect: Err(()),
4007            },
4008            TestCase {
4009                input: "--",
4010                expect: Err(()),
4011            },
4012            TestCase {
4013                input: "--c",
4014                expect: Err(()),
4015            },
4016            TestCase {
4017                input: "a=b",
4018                expect: Err(()),
4019            },
4020            TestCase {
4021                input: "--a=b",
4022                expect: Ok(("a", "b")),
4023            },
4024            TestCase {
4025                input: "--ca=b",
4026                expect: Ok(("ca", "b")),
4027            },
4028            TestCase {
4029                input: "-ca=b",
4030                expect: Ok(("a", "b")),
4031            },
4032            // Unclear what this should error, but at least test it.
4033            TestCase {
4034                input: "--=",
4035                expect: Ok(("", "")),
4036            },
4037        ];
4038        for test in tests {
4039            let got = parse_option(test.input);
4040            assert_eq!(got, test.expect, "input: {}", test.input);
4041        }
4042    }
4043
4044    #[mz_ore::test]
4045    fn test_split_options() {
4046        struct TestCase {
4047            input: &'static str,
4048            expect: Vec<&'static str>,
4049        }
4050        let tests = vec![
4051            TestCase {
4052                input: "",
4053                expect: vec![],
4054            },
4055            TestCase {
4056                input: "  ",
4057                expect: vec![],
4058            },
4059            TestCase {
4060                input: " a ",
4061                expect: vec!["a"],
4062            },
4063            TestCase {
4064                input: "  ab     cd   ",
4065                expect: vec!["ab", "cd"],
4066            },
4067            TestCase {
4068                input: r#"  ab\     cd   "#,
4069                expect: vec!["ab ", "cd"],
4070            },
4071            TestCase {
4072                input: r#"  ab\\     cd   "#,
4073                expect: vec![r#"ab\"#, "cd"],
4074            },
4075            TestCase {
4076                input: r#"  ab\\\     cd   "#,
4077                expect: vec![r#"ab\ "#, "cd"],
4078            },
4079            TestCase {
4080                input: r#"  ab\\\ cd   "#,
4081                expect: vec![r#"ab\ cd"#],
4082            },
4083            TestCase {
4084                input: r#"  ab\\\cd   "#,
4085                expect: vec![r#"ab\cd"#],
4086            },
4087            TestCase {
4088                input: r#"a\"#,
4089                expect: vec!["a"],
4090            },
4091            TestCase {
4092                input: r#"a\ "#,
4093                expect: vec!["a "],
4094            },
4095            TestCase {
4096                input: r#"\"#,
4097                expect: vec![],
4098            },
4099            TestCase {
4100                input: r#"\ "#,
4101                expect: vec![r#" "#],
4102            },
4103            TestCase {
4104                input: r#" \ "#,
4105                expect: vec![r#" "#],
4106            },
4107            TestCase {
4108                input: r#"\  "#,
4109                expect: vec![r#" "#],
4110            },
4111        ];
4112        for test in tests {
4113            let got = split_options(test.input);
4114            assert_eq!(got, test.expect, "input: {}", test.input);
4115        }
4116    }
4117
4118    #[mz_ore::test]
4119    fn test_is_jwt() {
4120        // A real JWT header decodes successfully.
4121        assert!(is_jwt("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.signature"));
4122        // Not JWTs: plain strings, wrong segment count, non-JSON headers.
4123        for s in [
4124            "",
4125            "secure_password",
4126            "p4ss.w0rd",
4127            "aaa.bbb.ccc",
4128            "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0",
4129            "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig.extra",
4130        ] {
4131            assert!(!is_jwt(s), "is_jwt({s:?})");
4132        }
4133    }
4134}