Skip to main content

mz_environmentd/http/
sql.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::net::{IpAddr, SocketAddr};
12use std::pin::pin;
13use std::sync::Arc;
14use std::time::Duration;
15
16use anyhow::anyhow;
17use async_trait::async_trait;
18use axum::extract::connect_info::ConnectInfo;
19use axum::extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket};
20use axum::extract::{State, WebSocketUpgrade};
21use axum::response::IntoResponse;
22use axum::{Extension, Json};
23use futures::Future;
24use futures::future::BoxFuture;
25
26use http::StatusCode;
27use itertools::Itertools;
28use mz_adapter::client::{RecordFirstRowStream, redact_sql_for_logging};
29use mz_adapter::session::{EndTransactionAction, TransactionStatus};
30use mz_adapter::statement_logging::{StatementEndedExecutionReason, StatementExecutionStrategy};
31use mz_adapter::{
32    AdapterError, AdapterNotice, ExecuteContextGuard, ExecuteResponse, ExecuteResponseKind,
33    PeekResponseUnary, SessionClient, verify_datum_desc,
34};
35use mz_auth::password::Password;
36use mz_catalog::memory::objects::{Cluster, ClusterReplica};
37use mz_interchange::encode::TypedDatum;
38use mz_interchange::json::{JsonNumberPolicy, ToJson};
39use mz_ore::cast::CastFrom;
40use mz_ore::metrics::{MakeCollectorOpts, MetricsRegistry};
41use mz_ore::result::ResultExt;
42use mz_ore::sql::Sql;
43use mz_repr::{Datum, RelationDesc, RowArena, RowIterator};
44use mz_sql::ast::display::AstDisplay;
45use mz_sql::ast::{CopyDirection, CopyStatement, CopyTarget, Raw, Statement, StatementKind};
46use mz_sql::parse::StatementParseResult;
47use mz_sql::plan::Plan;
48use mz_sql::session::metadata::SessionMetadata;
49use prometheus::Opts;
50use prometheus::core::{AtomicF64, GenericGaugeVec};
51use serde::{Deserialize, Serialize};
52use tokio::{select, time};
53use tokio_postgres::error::SqlState;
54use tower_sessions::Session as TowerSession;
55use tracing::{debug, info};
56use tungstenite::protocol::frame::coding::CloseCode;
57
58use crate::http::prometheus::PrometheusSqlQuery;
59use crate::http::{
60    AuthError, AuthedClient, AuthedUser, MAX_REQUEST_SIZE, WsState, ensure_session_unexpired,
61    init_ws, maybe_get_authenticated_session,
62};
63
64#[derive(Debug, thiserror::Error)]
65pub enum Error {
66    #[error(transparent)]
67    Adapter(#[from] AdapterError),
68    #[error(transparent)]
69    Json(#[from] serde_json::Error),
70    #[error(transparent)]
71    Axum(#[from] axum::Error),
72    #[error("SUBSCRIBE only supported over websocket")]
73    SubscribeOnlyOverWs,
74    #[error("current transaction is aborted, commands ignored until end of transaction block")]
75    AbortedTransaction,
76    #[error("unsupported via this API: {0}")]
77    Unsupported(String),
78    #[error("{0}")]
79    Unstructured(anyhow::Error),
80}
81
82impl Error {
83    pub fn detail(&self) -> Option<String> {
84        match self {
85            Error::Adapter(err) => err.detail(),
86            _ => None,
87        }
88    }
89
90    pub fn hint(&self) -> Option<String> {
91        match self {
92            Error::Adapter(err) => err.hint(),
93            _ => None,
94        }
95    }
96
97    pub fn position(&self) -> Option<usize> {
98        match self {
99            Error::Adapter(err) => err.position(),
100            _ => None,
101        }
102    }
103
104    pub fn code(&self) -> SqlState {
105        match self {
106            Error::Adapter(err) => err.code(),
107            Error::AbortedTransaction => SqlState::IN_FAILED_SQL_TRANSACTION,
108            _ => SqlState::INTERNAL_ERROR,
109        }
110    }
111}
112
113static PER_REPLICA_LABELS: &[&str] = &["replica_full_name", "instance_id", "replica_id"];
114
115async fn execute_promsql_query(
116    client: &mut AuthedClient,
117    query: &PrometheusSqlQuery<'_>,
118    metrics_registry: &MetricsRegistry,
119    metrics_by_name: &mut BTreeMap<String, GenericGaugeVec<AtomicF64>>,
120    cluster: Option<(&Cluster, &ClusterReplica)>,
121) {
122    assert_eq!(query.per_replica, cluster.is_some());
123
124    let mut res = SqlResponse {
125        results: Vec::new(),
126    };
127
128    execute_request(client, query.to_sql_request(cluster), &mut res)
129        .await
130        .expect("valid SQL query");
131
132    let result = match res.results.as_slice() {
133        // Each query issued is preceded by several SET commands
134        // to make sure it is routed to the right cluster replica.
135        [
136            SqlResult::Ok { .. },
137            SqlResult::Ok { .. },
138            SqlResult::Ok { .. },
139            result,
140        ] => result,
141        // Transient errors are fine, like if the cluster or replica
142        // was dropped before the promsql query was executed. We
143        // should not see errors in the steady state.
144        _ => {
145            info!(
146                "error executing prometheus query {}: {:?}",
147                query.metric_name, res
148            );
149            return;
150        }
151    };
152
153    let SqlResult::Rows { desc, rows, .. } = result else {
154        info!(
155            "did not receive rows for SQL query for prometheus metric {}: {:?}, {:?}",
156            query.metric_name, result, cluster
157        );
158        return;
159    };
160
161    let gauge_vec = metrics_by_name
162        .entry(query.metric_name.to_string())
163        .or_insert_with(|| {
164            let mut label_names: Vec<String> = desc
165                .columns
166                .iter()
167                .filter(|col| col.name != query.value_column_name)
168                .map(|col| col.name.clone())
169                .collect();
170
171            if query.per_replica {
172                label_names.extend(PER_REPLICA_LABELS.iter().map(|label| label.to_string()));
173            }
174
175            metrics_registry.register::<GenericGaugeVec<AtomicF64>>(MakeCollectorOpts {
176                opts: Opts::new(query.metric_name, query.help).variable_labels(label_names),
177                buckets: None,
178            })
179        });
180
181    for row in rows {
182        // Rows are stored as pre-serialized JSON arrays. Parse each one back to
183        // `Value`s here. Promsql results are tiny, so the parse cost is
184        // negligible.
185        let row: Vec<serde_json::Value> =
186            serde_json::from_str(row.get()).expect("row is a valid JSON array");
187
188        // Non-value columns become Prometheus label values. A SQL `NULL`
189        // arrives as JSON `null` and yields `None` from `as_str()`; fall back
190        // to an empty label rather than panicking. The query author is
191        // responsible for `COALESCE`ing nullable columns to a meaningful
192        // value; this is a defensive backstop.
193        let mut label_values = desc
194            .columns
195            .iter()
196            .zip_eq(&row)
197            .filter(|(col, _)| col.name != query.value_column_name)
198            .map(|(_, val)| val.as_str().unwrap_or(""))
199            .collect::<Vec<_>>();
200
201        let value = desc
202            .columns
203            .iter()
204            .zip_eq(&row)
205            .find(|(col, _)| col.name == query.value_column_name)
206            .map(|(_, val)| val.as_str().unwrap_or("0").parse::<f64>().unwrap_or(0.0))
207            .unwrap_or(0.0);
208
209        match cluster {
210            Some((cluster, replica)) => {
211                let replica_full_name = format!("{}.{}", cluster.name, replica.name);
212                let cluster_id = cluster.id.to_string();
213                let replica_id = replica.replica_id.to_string();
214
215                label_values.push(&replica_full_name);
216                label_values.push(&cluster_id);
217                label_values.push(&replica_id);
218
219                gauge_vec
220                    .get_metric_with_label_values(&label_values)
221                    .expect("valid labels")
222                    .set(value);
223            }
224            None => {
225                gauge_vec
226                    .get_metric_with_label_values(&label_values)
227                    .expect("valid labels")
228                    .set(value);
229            }
230        }
231    }
232}
233
234async fn handle_promsql_query(
235    client: &mut AuthedClient,
236    query: &PrometheusSqlQuery<'_>,
237    metrics_registry: &MetricsRegistry,
238    metrics_by_name: &mut BTreeMap<String, GenericGaugeVec<AtomicF64>>,
239) {
240    if !query.per_replica {
241        execute_promsql_query(client, query, metrics_registry, metrics_by_name, None).await;
242        return;
243    }
244
245    let catalog = client.client.catalog_snapshot("handle_promsql_query").await;
246    let clusters: Vec<&Cluster> = catalog.clusters().collect();
247
248    for cluster in clusters {
249        for replica in cluster.replicas() {
250            execute_promsql_query(
251                client,
252                query,
253                metrics_registry,
254                metrics_by_name,
255                Some((cluster, replica)),
256            )
257            .await;
258        }
259    }
260}
261
262pub async fn handle_promsql(
263    mut client: AuthedClient,
264    queries: &[PrometheusSqlQuery<'_>],
265) -> MetricsRegistry {
266    let metrics_registry = MetricsRegistry::new();
267    let mut metrics_by_name = BTreeMap::new();
268
269    for query in queries {
270        handle_promsql_query(&mut client, query, &metrics_registry, &mut metrics_by_name).await;
271    }
272
273    metrics_registry
274}
275
276pub async fn handle_sql(
277    mut client: AuthedClient,
278    Json(request): Json<SqlRequest>,
279) -> impl IntoResponse {
280    let mut res = SqlResponse {
281        results: Vec::new(),
282    };
283    // Don't need to worry about timeouts or resetting cancel here because there is always exactly 1
284    // request.
285    match execute_request(&mut client, request, &mut res).await {
286        Ok(()) => Ok(Json(res)),
287        Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())),
288    }
289}
290
291#[derive(Debug)]
292pub enum ExistingUser {
293    /// An AuthedUser provided by the
294    /// `x_materialize_user_header_auth` middleware
295    XMaterializeUserHeader(AuthedUser),
296    /// An AuthedUser provided by an authenticated session
297    /// established via [`crate::http::handle_login`].
298    Session(AuthedUser),
299}
300
301pub(crate) async fn handle_sql_ws(
302    State(state): State<WsState>,
303    existing_user: Option<Extension<AuthedUser>>,
304    ws: WebSocketUpgrade,
305    ConnectInfo(addr): ConnectInfo<SocketAddr>,
306    tower_session: Option<Extension<TowerSession>>,
307) -> Result<impl IntoResponse, AuthError> {
308    let session = tower_session.map(|Extension(session)| session);
309    // The `x_materialize_user_header_auth` middleware may have already provided the user for us
310    let user = match existing_user {
311        Some(Extension(user)) => Some(ExistingUser::XMaterializeUserHeader(user)),
312        None => {
313            let session = maybe_get_authenticated_session(session.as_ref()).await;
314            if let Some((session, session_data)) = session {
315                let user = ensure_session_unexpired(session, session_data).await?;
316                Some(ExistingUser::Session(user))
317            } else {
318                None
319            }
320        }
321    };
322
323    let addr = Box::new(addr.ip());
324    Ok(ws
325        .max_message_size(MAX_REQUEST_SIZE)
326        .on_upgrade(|ws| async move { run_ws(state, user, *addr, ws).await }))
327}
328
329#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
330#[serde(untagged)]
331pub enum WebSocketAuth {
332    Basic {
333        user: String,
334        password: Password,
335        #[serde(default)]
336        options: BTreeMap<String, String>,
337    },
338    Bearer {
339        token: String,
340        #[serde(default)]
341        options: BTreeMap<String, String>,
342    },
343    OptionsOnly {
344        #[serde(default)]
345        options: BTreeMap<String, String>,
346    },
347}
348
349async fn run_ws(state: WsState, user: Option<ExistingUser>, peer_addr: IpAddr, mut ws: WebSocket) {
350    let mut client = match init_ws(state, user, peer_addr, &mut ws).await {
351        Ok(client) => client,
352        Err(e) => {
353            // We omit most detail from the error message we send to the client, to
354            // avoid giving attackers unnecessary information during auth. AdapterErrors
355            // are safe to return because they're generated after authentication.
356            debug!("WS request failed init: {}", e);
357            let reason: Utf8Bytes = match e.downcast_ref::<AdapterError>() {
358                Some(error) => error.to_string().into(),
359                None => "unauthorized".to_string().into(),
360            };
361            let _ = ws
362                .send(Message::Close(Some(CloseFrame {
363                    code: CloseCode::Protocol.into(),
364                    reason,
365                })))
366                .await;
367            return;
368        }
369    };
370
371    // Successful auth, send startup messages.
372    let mut msgs = Vec::new();
373    let session = client.client.session();
374    for var in session.vars().notify_set() {
375        msgs.push(WebSocketResponse::ParameterStatus(ParameterStatus {
376            name: var.name().to_string(),
377            value: var.value(),
378        }));
379    }
380    msgs.push(WebSocketResponse::BackendKeyData(BackendKeyData {
381        conn_id: session.conn_id().unhandled(),
382        secret_key: session.secret_key(),
383    }));
384    msgs.push(WebSocketResponse::ReadyForQuery(
385        session.transaction_code().into(),
386    ));
387    for msg in msgs {
388        let _ = ws
389            .send(Message::Text(
390                serde_json::to_string(&msg).expect("must serialize").into(),
391            ))
392            .await;
393    }
394
395    // Send any notices that might have been generated on startup.
396    let notices = session.drain_notices();
397    if let Err(err) = forward_notices(&mut ws, notices).await {
398        debug!("failed to forward notices to WebSocket, {err:?}");
399        return;
400    }
401
402    loop {
403        // Handle timeouts first so we don't execute any statements when there's a pending timeout.
404        let msg = select! {
405            biased;
406
407            // `recv_timeout()` is cancel-safe as per it's docs.
408            Some(timeout) = client.client.recv_timeout() => {
409                client.client.terminate().await;
410                // We must wait for the client to send a request before we can send the error
411                // response. Although this isn't the PG wire protocol, we choose to mirror it by
412                // only sending errors as responses to requests.
413                let _ = ws.recv().await;
414                let err = Error::from(AdapterError::from(timeout));
415                let _ = send_ws_response(&mut ws, WebSocketResponse::Error(err.into())).await;
416                return;
417            },
418            message = ws.recv() => message,
419        };
420
421        client.client.remove_idle_in_transaction_session_timeout();
422
423        let msg = match msg {
424            Some(Ok(msg)) => msg,
425            _ => {
426                // client disconnected
427                return;
428            }
429        };
430
431        let req: Result<SqlRequest, Error> = match msg {
432            Message::Text(data) => serde_json::from_str(&data).err_into(),
433            Message::Binary(data) => serde_json::from_slice(&data).err_into(),
434            // Handled automatically by the server.
435            Message::Ping(_) => {
436                continue;
437            }
438            Message::Pong(_) => {
439                continue;
440            }
441            Message::Close(_) => {
442                return;
443            }
444        };
445
446        // Figure out if we need to send an error, any notices, but always the ready message.
447        let err = match run_ws_request(req, &mut client, &mut ws).await {
448            Ok(()) => None,
449            Err(err) => Some(WebSocketResponse::Error(err.into())),
450        };
451
452        // After running our request, there are several messages we need to send in a
453        // specific order.
454        //
455        // Note: we nest these into a closure so we can centralize our error handling
456        // for when sending over the WebSocket fails. We could also use a try {} block
457        // here, but those aren't stabilized yet.
458        let ws_response = || async {
459            // First respond with any error that might have occurred.
460            if let Some(e_resp) = err {
461                send_ws_response(&mut ws, e_resp).await?;
462            }
463
464            // Then forward along any notices we generated.
465            let notices = client.client.session().drain_notices();
466            forward_notices(&mut ws, notices).await?;
467
468            // Finally, respond that we're ready for the next query.
469            let ready =
470                WebSocketResponse::ReadyForQuery(client.client.session().transaction_code().into());
471            send_ws_response(&mut ws, ready).await?;
472
473            Ok::<_, Error>(())
474        };
475
476        if let Err(err) = ws_response().await {
477            debug!("failed to send response over WebSocket, {err:?}");
478            return;
479        }
480    }
481}
482
483async fn run_ws_request(
484    req: Result<SqlRequest, Error>,
485    client: &mut AuthedClient,
486    ws: &mut WebSocket,
487) -> Result<(), Error> {
488    let req = req?;
489    execute_request(client, req, ws).await
490}
491
492/// Sends a single [`WebSocketResponse`] over the provided [`WebSocket`].
493async fn send_ws_response(ws: &mut WebSocket, resp: WebSocketResponse) -> Result<(), Error> {
494    let msg = serde_json::to_string(&resp).unwrap();
495    let msg = Message::Text(msg.into());
496    ws.send(msg).await?;
497
498    Ok(())
499}
500
501/// Forwards a collection of Notices to the provided [`WebSocket`].
502async fn forward_notices(
503    ws: &mut WebSocket,
504    notices: impl IntoIterator<Item = AdapterNotice>,
505) -> Result<(), Error> {
506    let ws_notices = notices.into_iter().map(|notice| {
507        WebSocketResponse::Notice(Notice {
508            message: notice.to_string(),
509            code: notice.code().code().to_string(),
510            severity: notice.severity().as_str().to_lowercase(),
511            detail: notice.detail(),
512            hint: notice.hint(),
513        })
514    });
515
516    for notice in ws_notices {
517        send_ws_response(ws, notice).await?;
518    }
519
520    Ok(())
521}
522
523/// A request to execute SQL over HTTP.
524#[derive(Serialize, Deserialize, Debug)]
525#[serde(untagged)]
526pub enum SqlRequest {
527    /// A simple query request.
528    Simple {
529        /// A query string containing zero or more queries delimited by
530        /// semicolons.
531        query: Sql,
532    },
533    /// An extended query request.
534    Extended {
535        /// Queries to execute using the extended protocol.
536        queries: Vec<ExtendedRequest>,
537    },
538}
539
540/// An request to execute a SQL query using the extended protocol.
541#[derive(Serialize, Deserialize, Debug)]
542pub struct ExtendedRequest {
543    /// A query string containing zero or one queries.
544    query: String,
545    /// Optional parameters for the query.
546    #[serde(default)]
547    params: Vec<Option<String>>,
548}
549
550/// The response to a `SqlRequest`.
551#[derive(Debug, Serialize, Deserialize)]
552pub struct SqlResponse {
553    /// The results for each query in the request.
554    pub(in crate::http) results: Vec<SqlResult>,
555}
556
557impl SqlResponse {
558    /// Creates a new empty SqlResponse for collecting results.
559    pub(in crate::http) fn new() -> Self {
560        Self {
561            results: Vec::new(),
562        }
563    }
564}
565
566pub(in crate::http) enum StatementResult {
567    SqlResult(SqlResult),
568    /// A peek (`SELECT`) result whose rows are streamed out of the peek response
569    /// stash. The stream is consumed lazily by the sender so a large result is
570    /// not buffered whole. Contrast `SqlResult::Rows`, which holds
571    /// already-collected rows and exists only for the buffered JSON transport.
572    Rows {
573        desc: RelationDesc,
574        rows_stream: RecordFirstRowStream,
575        max_result_size: usize,
576    },
577    Subscribe {
578        desc: RelationDesc,
579        tag: String,
580        rx: RecordFirstRowStream,
581        ctx_extra: ExecuteContextGuard,
582    },
583}
584
585impl From<SqlResult> for StatementResult {
586    fn from(inner: SqlResult) -> Self {
587        Self::SqlResult(inner)
588    }
589}
590
591/// The result of a single query in a [`SqlResponse`].
592#[derive(Debug, Serialize, Deserialize)]
593#[serde(untagged)]
594pub enum SqlResult {
595    /// The query returned rows.
596    Rows {
597        /// The command complete tag.
598        tag: String,
599        /// The result rows, each already serialized to a compact JSON array.
600        ///
601        /// We accumulate pre-serialized rows rather than a `serde_json::Value`
602        /// tree so the buffered footprint stays close to the wire size. A
603        /// `Value` tree is ~10-15x larger (each cell a heap `Value`, in a
604        /// per-row `Vec`, in the outer `Vec`), which is what let a large
605        /// `SELECT` over the JSON endpoint OOM the process. `RawValue`
606        /// re-serializes verbatim, so the wire format is unchanged.
607        rows: Vec<Box<serde_json::value::RawValue>>,
608        /// Information about each column.
609        desc: Description,
610        // Any notices generated during execution of the query.
611        notices: Vec<Notice>,
612    },
613    /// The query executed successfully but did not return rows.
614    Ok {
615        /// The command complete tag.
616        ok: String,
617        /// Any notices generated during execution of the query.
618        notices: Vec<Notice>,
619        /// Any parameters that may have changed.
620        ///
621        /// Note: skip serializing this field in a response if the list of parameters is empty.
622        #[serde(skip_serializing_if = "Vec::is_empty")]
623        parameters: Vec<ParameterStatus>,
624    },
625    /// The query returned an error.
626    Err {
627        error: SqlError,
628        // Any notices generated during execution of the query.
629        notices: Vec<Notice>,
630    },
631}
632
633impl SqlResult {
634    /// Convert adapter Row results into the buffered web row result format. Error
635    /// if the row format does not match the expected descriptor, or if the
636    /// result exceeds `max_query_result_size`.
637    ///
638    /// This buffers the whole result, so it is used only by the JSON transport,
639    /// whose response is a single document. The WebSocket transport streams rows
640    /// through `StatementResult::Rows` and never calls this. The size guard
641    /// counts `Row::byte_len`, matching the WebSocket transport and pgwire, and
642    /// rows are stored as pre-serialized compact `RawValue`s to avoid the
643    /// amplified `Value`-tree buffering that could OOM.
644    async fn rows<S>(
645        sender: &mut S,
646        client: &mut SessionClient,
647        mut rows_stream: RecordFirstRowStream,
648        max_query_result_size: usize,
649        desc: &RelationDesc,
650    ) -> Result<SqlResult, Error>
651    where
652        S: ResultSender,
653    {
654        let mut rows: Vec<Box<serde_json::value::RawValue>> = vec![];
655        let mut datum_vec = mz_repr::DatumVec::new();
656        let types = &desc.typ().column_types;
657
658        let mut query_result_size: usize = 0;
659
660        loop {
661            let peek_response = tokio::select! {
662                notice = client.session().recv_notice(), if S::SUPPORTS_STREAMING_NOTICES => {
663                    sender.emit_streaming_notices(vec![notice]).await?;
664                    continue;
665                }
666                e = sender.connection_error() => return Err(e),
667                r = rows_stream.recv() => {
668                    match r {
669                        Some(r) => r,
670                        None => break,
671                    }
672                },
673            };
674
675            let mut sql_rows = match peek_response {
676                PeekResponseUnary::Rows(rows) => rows,
677                PeekResponseUnary::Error(e) => {
678                    return Ok(SqlResult::err(client, e));
679                }
680                PeekResponseUnary::DependencyDropped(dep) => {
681                    return Ok(SqlResult::err(client, dep.to_concurrent_dependency_drop()));
682                }
683                PeekResponseUnary::Canceled => {
684                    return Ok(SqlResult::err(client, AdapterError::Canceled));
685                }
686            };
687
688            if let Err(err) = verify_datum_desc(desc, &mut sql_rows) {
689                return Ok(SqlResult::Err {
690                    error: err.into(),
691                    notices: make_notices(client),
692                });
693            }
694
695            while let Some(row) = sql_rows.next() {
696                // Enforce `max_result_size` on `Row::byte_len`, the same quantity
697                // pgwire and the WebSocket transport use, so the cap means one
698                // thing across every transport.
699                query_result_size = query_result_size.saturating_add(row.byte_len());
700                if query_result_size > max_query_result_size {
701                    use bytesize::ByteSize;
702                    return Ok(SqlResult::err(
703                        client,
704                        AdapterError::ResultSize(format!(
705                            "result exceeds max size of {}",
706                            ByteSize::b(u64::cast_from(max_query_result_size))
707                        )),
708                    ));
709                }
710                let datums = datum_vec.borrow_with(row);
711                let json_row: Vec<serde_json::Value> = datums
712                    .iter()
713                    .enumerate()
714                    .map(|(i, d)| {
715                        TypedDatum::new(*d, &types[i])
716                            .json(&JsonNumberPolicy::ConvertNumberToString)
717                    })
718                    .collect();
719                // Keep only the compact serialized JSON text. The transient
720                // `Value` tree above is dropped per row, so at most one row's tree
721                // is resident, avoiding the amplified buffering that could OOM.
722                let raw = serde_json::value::to_raw_value(&json_row)
723                    .expect("row of JSON values always serializes");
724                rows.push(raw);
725            }
726        }
727
728        let tag = format!("SELECT {}", rows.len());
729        Ok(SqlResult::Rows {
730            tag,
731            rows,
732            desc: Description::from(desc),
733            notices: make_notices(client),
734        })
735    }
736
737    fn err(client: &mut SessionClient, error: impl Into<SqlError>) -> SqlResult {
738        SqlResult::Err {
739            error: error.into(),
740            notices: make_notices(client),
741        }
742    }
743
744    fn ok(client: &mut SessionClient, tag: String, params: Vec<ParameterStatus>) -> SqlResult {
745        SqlResult::Ok {
746            ok: tag,
747            parameters: params,
748            notices: make_notices(client),
749        }
750    }
751}
752
753#[derive(Debug, Deserialize, Serialize)]
754pub struct SqlError {
755    pub message: String,
756    pub code: String,
757    #[serde(skip_serializing_if = "Option::is_none")]
758    pub detail: Option<String>,
759    #[serde(skip_serializing_if = "Option::is_none")]
760    pub hint: Option<String>,
761    #[serde(skip_serializing_if = "Option::is_none")]
762    pub position: Option<usize>,
763}
764
765impl From<Error> for SqlError {
766    fn from(err: Error) -> Self {
767        SqlError {
768            message: err.to_string(),
769            code: err.code().code().to_string(),
770            detail: err.detail(),
771            hint: err.hint(),
772            position: err.position(),
773        }
774    }
775}
776
777impl From<AdapterError> for SqlError {
778    fn from(value: AdapterError) -> Self {
779        Error::from(value).into()
780    }
781}
782
783#[derive(Debug, Deserialize, Serialize)]
784#[serde(tag = "type", content = "payload")]
785pub enum WebSocketResponse {
786    ReadyForQuery(String),
787    Notice(Notice),
788    Rows(Description),
789    Row(Vec<serde_json::Value>),
790    CommandStarting(CommandStarting),
791    CommandComplete(String),
792    Error(SqlError),
793    ParameterStatus(ParameterStatus),
794    BackendKeyData(BackendKeyData),
795}
796
797#[derive(Debug, Serialize, Deserialize)]
798pub struct Notice {
799    message: String,
800    code: String,
801    severity: String,
802    #[serde(skip_serializing_if = "Option::is_none")]
803    pub detail: Option<String>,
804    #[serde(skip_serializing_if = "Option::is_none")]
805    pub hint: Option<String>,
806}
807
808impl Notice {
809    pub fn message(&self) -> &str {
810        &self.message
811    }
812}
813
814#[derive(Debug, Serialize, Deserialize)]
815pub struct Description {
816    pub columns: Vec<Column>,
817}
818
819impl From<&RelationDesc> for Description {
820    fn from(desc: &RelationDesc) -> Self {
821        let columns = desc
822            .iter()
823            .map(|(name, typ)| {
824                let pg_type = mz_pgrepr::Type::from(&typ.scalar_type);
825                Column {
826                    name: name.to_string(),
827                    type_oid: pg_type.oid(),
828                    type_len: pg_type.typlen(),
829                    type_mod: pg_type.typmod(),
830                }
831            })
832            .collect();
833        Description { columns }
834    }
835}
836
837#[derive(Debug, Serialize, Deserialize)]
838pub struct Column {
839    pub name: String,
840    pub type_oid: u32,
841    pub type_len: i16,
842    pub type_mod: i32,
843}
844
845#[derive(Debug, Serialize, Deserialize)]
846pub struct ParameterStatus {
847    name: String,
848    value: String,
849}
850
851#[derive(Debug, Serialize, Deserialize)]
852pub struct BackendKeyData {
853    conn_id: u32,
854    secret_key: u32,
855}
856
857#[derive(Debug, Serialize, Deserialize)]
858pub struct CommandStarting {
859    has_rows: bool,
860    is_streaming: bool,
861}
862
863/// Trait describing how to transmit a response to a client. HTTP clients
864/// accumulate into a Vec and send all at once. WebSocket clients send each
865/// message as they occur.
866#[async_trait]
867pub(in crate::http) trait ResultSender: Send {
868    const SUPPORTS_STREAMING_NOTICES: bool = false;
869
870    /// Adds a result to the client. The first component of the return value is
871    /// Err if sending to the client
872    /// produced an error and the server should disconnect. It is Ok(Err) if the statement
873    /// produced an error and should error the transaction, but remain connected. It is Ok(Ok(()))
874    /// if the statement succeeded.
875    /// The second component of the return value is `Some` if execution still
876    /// needs to be retired for statement logging purposes.
877    async fn add_result(
878        &mut self,
879        client: &mut SessionClient,
880        res: StatementResult,
881    ) -> (
882        Result<Result<(), ()>, Error>,
883        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
884    );
885
886    /// Returns a future that resolves only when the client connection has gone away.
887    fn connection_error(&mut self) -> BoxFuture<'_, Error>;
888    /// Reports whether the client supports streaming SUBSCRIBE results.
889    fn allow_subscribe(&self) -> bool;
890
891    /// Emits a streaming notice if the sender supports it.
892    ///
893    /// Does nothing if `SUPPORTS_STREAMING_NOTICES` is false.
894    async fn emit_streaming_notices(&mut self, _: Vec<AdapterNotice>) -> Result<(), Error> {
895        unreachable!("streaming notices marked as unsupported")
896    }
897}
898
899#[async_trait]
900impl ResultSender for SqlResponse {
901    // The first component of the return value is
902    // Err if sending to the client
903    // produced an error and the server should disconnect. It is Ok(Err) if the statement
904    // produced an error and should error the transaction, but remain connected. It is Ok(Ok(()))
905    // if the statement succeeded.
906    // The second component of the return value is `Some` if execution still
907    // needs to be retired for statement logging purposes.
908    async fn add_result(
909        &mut self,
910        client: &mut SessionClient,
911        res: StatementResult,
912    ) -> (
913        Result<Result<(), ()>, Error>,
914        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
915    ) {
916        let (res, stmt_logging) = match res {
917            StatementResult::SqlResult(res) => {
918                let is_err = matches!(res, SqlResult::Err { .. });
919                self.results.push(res);
920                let res = if is_err { Err(()) } else { Ok(()) };
921                (res, None)
922            }
923            StatementResult::Rows {
924                desc,
925                rows_stream,
926                max_result_size,
927            } => {
928                // The JSON transport is a single buffered document, so the rows
929                // must be collected before the response is serialized.
930                // `SqlResult::rows` bounds that buffer against `max_result_size`.
931                let res = match SqlResult::rows(self, client, rows_stream, max_result_size, &desc)
932                    .await
933                {
934                    Ok(res) => res,
935                    Err(e) => return (Err(e), None),
936                };
937                let is_err = matches!(res, SqlResult::Err { .. });
938                self.results.push(res);
939                let res = if is_err { Err(()) } else { Ok(()) };
940                (res, None)
941            }
942            StatementResult::Subscribe { ctx_extra, .. } => {
943                let message = "SUBSCRIBE only supported over websocket";
944                self.results.push(SqlResult::Err {
945                    error: Error::SubscribeOnlyOverWs.into(),
946                    notices: Vec::new(),
947                });
948                (
949                    Err(()),
950                    Some((
951                        StatementEndedExecutionReason::Errored {
952                            error: message.into(),
953                        },
954                        ctx_extra,
955                    )),
956                )
957            }
958        };
959        (Ok(res), stmt_logging)
960    }
961
962    fn connection_error(&mut self) -> BoxFuture<'_, Error> {
963        Box::pin(futures::future::pending())
964    }
965
966    fn allow_subscribe(&self) -> bool {
967        false
968    }
969}
970
971#[async_trait]
972impl ResultSender for WebSocket {
973    const SUPPORTS_STREAMING_NOTICES: bool = true;
974
975    // The first component of the return value is Err if sending to the client produced an error and
976    // the server should disconnect. It is Ok(Err) if the statement produced an error and should
977    // error the transaction, but remain connected. It is Ok(Ok(())) if the statement succeeded. The
978    // second component of the return value is `Some` if execution still needs to be retired for
979    // statement logging purposes.
980    async fn add_result(
981        &mut self,
982        client: &mut SessionClient,
983        res: StatementResult,
984    ) -> (
985        Result<Result<(), ()>, Error>,
986        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
987    ) {
988        let (has_rows, is_streaming) = match res {
989            StatementResult::SqlResult(SqlResult::Err { .. }) => (false, false),
990            StatementResult::SqlResult(SqlResult::Ok { .. }) => (false, false),
991            StatementResult::SqlResult(SqlResult::Rows { .. }) => (true, false),
992            StatementResult::Rows { .. } => (true, false),
993            StatementResult::Subscribe { .. } => (true, true),
994        };
995        if let Err(e) = send_ws_response(
996            self,
997            WebSocketResponse::CommandStarting(CommandStarting {
998                has_rows,
999                is_streaming,
1000            }),
1001        )
1002        .await
1003        {
1004            return (Err(e), None);
1005        }
1006
1007        let (is_err, msgs, stmt_logging) = match res {
1008            StatementResult::SqlResult(SqlResult::Rows { .. }) => {
1009                // `SqlResult::Rows` holds already-collected rows for the buffered
1010                // JSON transport only. The WebSocket transport streams peek
1011                // results through `StatementResult::Rows` and never materializes
1012                // a `SqlResult::Rows`.
1013                unreachable!("WebSocket streams peek rows via StatementResult::Rows")
1014            }
1015            StatementResult::Rows {
1016                ref desc,
1017                mut rows_stream,
1018                max_result_size,
1019            } => match stream_ws_peek_rows(self, client, desc, &mut rows_stream, max_result_size)
1020                .await
1021            {
1022                Ok(result) => result,
1023                // A write failure means the remote broke the connection, which we
1024                // treat as a cancellation to match pgwire.
1025                Err(e) => return (Err(e), None),
1026            },
1027            StatementResult::SqlResult(SqlResult::Ok {
1028                ok,
1029                parameters,
1030                notices,
1031            }) => {
1032                let mut msgs = vec![WebSocketResponse::CommandComplete(ok)];
1033                msgs.extend(notices.into_iter().map(WebSocketResponse::Notice));
1034                msgs.extend(
1035                    parameters
1036                        .into_iter()
1037                        .map(WebSocketResponse::ParameterStatus),
1038                );
1039                (false, msgs, None)
1040            }
1041            StatementResult::SqlResult(SqlResult::Err { error, notices }) => {
1042                let mut msgs = vec![WebSocketResponse::Error(error)];
1043                msgs.extend(notices.into_iter().map(WebSocketResponse::Notice));
1044                (true, msgs, None)
1045            }
1046            StatementResult::Subscribe {
1047                ref desc,
1048                tag,
1049                mut rx,
1050                ctx_extra,
1051            } => {
1052                if let Err(e) = send_ws_response(self, WebSocketResponse::Rows(desc.into())).await {
1053                    // We consider the remote breaking the connection to be a cancellation,
1054                    // matching the behavior for pgwire
1055                    return (
1056                        Err(e),
1057                        Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1058                    );
1059                }
1060
1061                let mut datum_vec = mz_repr::DatumVec::new();
1062                let mut result_size: usize = 0;
1063                let mut rows_returned = 0;
1064                loop {
1065                    let res = match await_rows(self, client, rx.recv()).await {
1066                        Ok(res) => res,
1067                        Err(e) => {
1068                            // We consider the remote breaking the connection to be a cancellation,
1069                            // matching the behavior for pgwire
1070                            return (
1071                                Err(e),
1072                                Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1073                            );
1074                        }
1075                    };
1076                    match res {
1077                        Some(PeekResponseUnary::Rows(mut rows)) => {
1078                            if let Err(err) = verify_datum_desc(desc, &mut rows) {
1079                                let error = err.to_string();
1080                                break (
1081                                    true,
1082                                    vec![WebSocketResponse::Error(err.into())],
1083                                    Some((
1084                                        StatementEndedExecutionReason::Errored { error },
1085                                        ctx_extra,
1086                                    )),
1087                                );
1088                            }
1089
1090                            rows_returned += rows.count();
1091                            while let Some(row) = rows.next() {
1092                                result_size = result_size.saturating_add(row.byte_len());
1093                                let datums = datum_vec.borrow_with(row);
1094                                let types = &desc.typ().column_types;
1095                                if let Err(e) = send_ws_response(
1096                                    self,
1097                                    WebSocketResponse::Row(
1098                                        datums
1099                                            .iter()
1100                                            .enumerate()
1101                                            .map(|(i, d)| {
1102                                                TypedDatum::new(*d, &types[i])
1103                                                    .json(&JsonNumberPolicy::ConvertNumberToString)
1104                                            })
1105                                            .collect(),
1106                                    ),
1107                                )
1108                                .await
1109                                {
1110                                    // We consider the remote breaking the connection to be a cancellation,
1111                                    // matching the behavior for pgwire
1112                                    return (
1113                                        Err(e),
1114                                        Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1115                                    );
1116                                }
1117                            }
1118                        }
1119                        Some(PeekResponseUnary::Error(err)) => {
1120                            let error = err.to_string();
1121                            break (
1122                                true,
1123                                vec![WebSocketResponse::Error(err.into())],
1124                                Some((StatementEndedExecutionReason::Errored { error }, ctx_extra)),
1125                            );
1126                        }
1127                        Some(PeekResponseUnary::DependencyDropped(dep)) => {
1128                            let err = dep.to_concurrent_dependency_drop();
1129                            let error = err.to_string();
1130                            break (
1131                                true,
1132                                vec![WebSocketResponse::Error(err.into())],
1133                                Some((StatementEndedExecutionReason::Errored { error }, ctx_extra)),
1134                            );
1135                        }
1136                        Some(PeekResponseUnary::Canceled) => {
1137                            break (
1138                                true,
1139                                vec![WebSocketResponse::Error(AdapterError::Canceled.into())],
1140                                Some((StatementEndedExecutionReason::Canceled, ctx_extra)),
1141                            );
1142                        }
1143                        None => {
1144                            break (
1145                                false,
1146                                vec![WebSocketResponse::CommandComplete(tag)],
1147                                Some((
1148                                    StatementEndedExecutionReason::Success {
1149                                        result_size: Some(u64::cast_from(result_size)),
1150                                        rows_returned: Some(u64::cast_from(rows_returned)),
1151                                        execution_strategy: Some(
1152                                            StatementExecutionStrategy::Standard,
1153                                        ),
1154                                    },
1155                                    ctx_extra,
1156                                )),
1157                            );
1158                        }
1159                    }
1160                }
1161            }
1162        };
1163        for msg in msgs {
1164            if let Err(e) = send_ws_response(self, msg).await {
1165                return (
1166                    Err(e),
1167                    stmt_logging.map(|(_old_reason, ctx_extra)| {
1168                        (StatementEndedExecutionReason::Canceled, ctx_extra)
1169                    }),
1170                );
1171            }
1172        }
1173        (Ok(if is_err { Err(()) } else { Ok(()) }), stmt_logging)
1174    }
1175
1176    // Send a websocket Ping every second to verify the client is still
1177    // connected.
1178    fn connection_error(&mut self) -> BoxFuture<'_, Error> {
1179        Box::pin(async {
1180            let mut tick = time::interval(Duration::from_secs(1));
1181            tick.tick().await;
1182            loop {
1183                tick.tick().await;
1184                if let Err(err) = self.send(Message::Ping(Vec::new().into())).await {
1185                    return err.into();
1186                }
1187            }
1188        })
1189    }
1190
1191    fn allow_subscribe(&self) -> bool {
1192        true
1193    }
1194
1195    async fn emit_streaming_notices(&mut self, notices: Vec<AdapterNotice>) -> Result<(), Error> {
1196        forward_notices(self, notices).await
1197    }
1198}
1199
1200async fn await_rows<S, F, R>(sender: &mut S, client: &mut SessionClient, f: F) -> Result<R, Error>
1201where
1202    S: ResultSender,
1203    F: Future<Output = R> + Send,
1204{
1205    let mut f = pin!(f);
1206    loop {
1207        tokio::select! {
1208            notice = client.session().recv_notice(), if S::SUPPORTS_STREAMING_NOTICES => {
1209                sender.emit_streaming_notices(vec![notice]).await?;
1210            }
1211            e = sender.connection_error() => return Err(e),
1212            r = &mut f => return Ok(r),
1213        }
1214    }
1215}
1216
1217/// Streams a peek (`SELECT`) result to a WebSocket client one stash batch at a
1218/// time, flushing between batches so a slow client applies real backpressure
1219/// and only one batch is resident. This gives a large `SELECT` over WebSocket
1220/// the same bounded memory profile as pgwire `SELECT`, and mirrors the
1221/// `Subscribe` arm of `WebSocket::add_result`.
1222///
1223/// On success returns the `(is_err, msgs, stmt_logging)` triple that
1224/// `add_result` folds into its response. An `Err` means a write to the socket
1225/// failed, so the server should disconnect. `add_result` turns that into a
1226/// cancellation to match pgwire.
1227///
1228/// The `Rows` descriptor is sent lazily, right before the first batch of rows
1229/// or an empty successful result, but never before an error. So a query that
1230/// fails before producing any rows emits only an `Error`.
1231async fn stream_ws_peek_rows(
1232    ws: &mut WebSocket,
1233    client: &mut SessionClient,
1234    desc: &RelationDesc,
1235    rows_stream: &mut RecordFirstRowStream,
1236    max_result_size: usize,
1237) -> Result<
1238    (
1239        bool,
1240        Vec<WebSocketResponse>,
1241        Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
1242    ),
1243    Error,
1244> {
1245    let mut datum_vec = mz_repr::DatumVec::new();
1246    let mut result_size: usize = 0;
1247    let mut rows_returned: usize = 0;
1248    let mut sent_rows_desc = false;
1249    loop {
1250        // Bind before matching so the `Option<PeekResponseUnary>` (which has a
1251        // significant `Drop`) is not a temporary living for the whole match.
1252        let res = await_rows(ws, client, rows_stream.recv()).await?;
1253        match res {
1254            Some(PeekResponseUnary::Rows(mut rows)) => {
1255                if let Err(err) = verify_datum_desc(desc, &mut rows) {
1256                    return Ok(ws_peek_result(
1257                        client,
1258                        true,
1259                        vec![WebSocketResponse::Error(err.into())],
1260                    ));
1261                }
1262                // The header waits until a batch has passed `verify_datum_desc`,
1263                // so a query that fails before producing any rows emits only an
1264                // `Error`. Sending it before the loop, as the `Subscribe` arm
1265                // does, would put a `Rows` header in front of that `Error`.
1266                if !sent_rows_desc {
1267                    send_ws_response(ws, WebSocketResponse::Rows(desc.into())).await?;
1268                    sent_rows_desc = true;
1269                }
1270                let types = &desc.typ().column_types;
1271                while let Some(row) = rows.next() {
1272                    result_size = result_size.saturating_add(row.byte_len());
1273                    if result_size > max_result_size {
1274                        use bytesize::ByteSize;
1275                        return Ok(ws_peek_result(
1276                            client,
1277                            true,
1278                            vec![WebSocketResponse::Error(
1279                                AdapterError::ResultSize(format!(
1280                                    "result exceeds max size of {}",
1281                                    ByteSize::b(u64::cast_from(max_result_size))
1282                                ))
1283                                .into(),
1284                            )],
1285                        ));
1286                    }
1287                    let datums = datum_vec.borrow_with(row);
1288                    send_ws_response(
1289                        ws,
1290                        WebSocketResponse::Row(
1291                            datums
1292                                .iter()
1293                                .enumerate()
1294                                .map(|(i, d)| {
1295                                    TypedDatum::new(*d, &types[i])
1296                                        .json(&JsonNumberPolicy::ConvertNumberToString)
1297                                })
1298                                .collect(),
1299                        ),
1300                    )
1301                    .await?;
1302                    rows_returned += 1;
1303                }
1304            }
1305            Some(PeekResponseUnary::Error(error)) => {
1306                return Ok(ws_peek_result(
1307                    client,
1308                    true,
1309                    vec![WebSocketResponse::Error(error.into())],
1310                ));
1311            }
1312            Some(PeekResponseUnary::DependencyDropped(dep)) => {
1313                return Ok(ws_peek_result(
1314                    client,
1315                    true,
1316                    vec![WebSocketResponse::Error(
1317                        dep.to_concurrent_dependency_drop().into(),
1318                    )],
1319                ));
1320            }
1321            Some(PeekResponseUnary::Canceled) => {
1322                return Ok(ws_peek_result(
1323                    client,
1324                    true,
1325                    vec![WebSocketResponse::Error(AdapterError::Canceled.into())],
1326                ));
1327            }
1328            None => {
1329                // An empty successful result still owes the client a `Rows`
1330                // descriptor before `CommandComplete`.
1331                if !sent_rows_desc {
1332                    send_ws_response(ws, WebSocketResponse::Rows(desc.into())).await?;
1333                }
1334                return Ok(ws_peek_result(
1335                    client,
1336                    false,
1337                    vec![WebSocketResponse::CommandComplete(format!(
1338                        "SELECT {rows_returned}"
1339                    ))],
1340                ));
1341            }
1342        }
1343    }
1344}
1345
1346/// Packages a terminal result of `stream_ws_peek_rows`, appending any notices
1347/// still buffered on the session after `msgs`.
1348///
1349/// The streaming loop forwards notices live through `await_rows`' `recv_notice`
1350/// select, but the terminal `recv() -> None` can race a still-buffered notice
1351/// and end the loop first. Draining here restores the buffered path's guarantee
1352/// that all notices reach the client, after `CommandComplete` or `Error`.
1353fn ws_peek_result(
1354    client: &mut SessionClient,
1355    is_err: bool,
1356    mut msgs: Vec<WebSocketResponse>,
1357) -> (
1358    bool,
1359    Vec<WebSocketResponse>,
1360    Option<(StatementEndedExecutionReason, ExecuteContextGuard)>,
1361) {
1362    msgs.extend(
1363        make_notices(client)
1364            .into_iter()
1365            .map(WebSocketResponse::Notice),
1366    );
1367    (is_err, msgs, None)
1368}
1369
1370async fn send_and_retire<S: ResultSender>(
1371    res: StatementResult,
1372    client: &mut SessionClient,
1373    sender: &mut S,
1374) -> Result<Result<(), ()>, Error> {
1375    let (res, stmt_logging) = sender.add_result(client, res).await;
1376    if let Some((reason, ctx_extra)) = stmt_logging {
1377        client.retire_execute(ctx_extra, reason);
1378    }
1379    res
1380}
1381
1382/// Returns Ok(Err) if any statement error'd during execution.
1383async fn execute_stmt_group<S: ResultSender>(
1384    client: &mut SessionClient,
1385    sender: &mut S,
1386    stmt_group: Vec<(Statement<Raw>, String, Vec<Option<String>>)>,
1387) -> Result<Result<(), ()>, Error> {
1388    let num_stmts = stmt_group.len();
1389    for (stmt, sql, params) in stmt_group {
1390        assert!(
1391            num_stmts <= 1 || params.is_empty(),
1392            "statement groups contain more than 1 statement iff Simple request, which does not support parameters"
1393        );
1394
1395        let is_aborted_txn = matches!(client.session().transaction(), TransactionStatus::Failed(_));
1396        if is_aborted_txn && !is_txn_exit_stmt(&stmt) {
1397            let err = SqlResult::err(client, Error::AbortedTransaction);
1398            let _ = send_and_retire(err.into(), client, sender).await?;
1399            return Ok(Err(()));
1400        }
1401
1402        // Mirror the behavior of the PostgreSQL simple query protocol.
1403        // See the pgwire::protocol::StateMachine::query method for details.
1404        if let Err(e) = client.start_transaction(Some(num_stmts)) {
1405            let err = SqlResult::err(client, e);
1406            let _ = send_and_retire(err.into(), client, sender).await?;
1407            return Ok(Err(()));
1408        }
1409        let res = execute_stmt(client, sender, stmt, sql, params).await?;
1410        let is_err = send_and_retire(res, client, sender).await?;
1411
1412        if is_err.is_err() {
1413            // Mirror StateMachine::error, which sometimes will clean up the
1414            // transaction state instead of always leaving it in Failed.
1415            let txn = client.session().transaction();
1416            match txn {
1417                // Error can be called from describe and parse and so might not be in an active
1418                // transaction.
1419                TransactionStatus::Default | TransactionStatus::Failed(_) => {}
1420                // In Started (i.e., a single statement) and implicit transactions cleanup themselves.
1421                TransactionStatus::Started(_) | TransactionStatus::InTransactionImplicit(_) => {
1422                    if let Err(err) = client.end_transaction(EndTransactionAction::Rollback).await {
1423                        let err = SqlResult::err(client, err);
1424                        let _ = send_and_retire(err.into(), client, sender).await?;
1425                    }
1426                }
1427                // Explicit transactions move to failed.
1428                TransactionStatus::InTransaction(_) => {
1429                    client.fail_transaction();
1430                }
1431            }
1432            return Ok(Err(()));
1433        }
1434    }
1435    Ok(Ok(()))
1436}
1437
1438/// Executes an entire [`SqlRequest`].
1439///
1440/// See the user-facing documentation about the HTTP API for a description of
1441/// the semantics of this function.
1442/// Executes a SQL request and sends results to the provided sender.
1443///
1444/// Made visible to http submodules (like mcp) via `pub(in crate::http)` to allow
1445/// reuse of SQL execution logic.
1446pub(in crate::http) async fn execute_request<S: ResultSender>(
1447    client: &mut AuthedClient,
1448    request: SqlRequest,
1449    sender: &mut S,
1450) -> Result<(), Error> {
1451    let client = &mut client.client;
1452
1453    if client.statement_arrival_logging_enabled().await {
1454        let session = client.session();
1455        let conn_id = session.conn_id();
1456        let session_uuid = session.uuid();
1457        match &request {
1458            SqlRequest::Simple { query } => {
1459                info!(
1460                    %conn_id, %session_uuid, kind = "http_simple",
1461                    sql = %redact_sql_for_logging(query.as_str()),
1462                    "statement arrival"
1463                );
1464            }
1465            SqlRequest::Extended { queries } => {
1466                for ExtendedRequest { query, params } in queries {
1467                    // Parameter values are data that redaction cannot reach,
1468                    // so only their count is logged.
1469                    info!(
1470                        %conn_id, %session_uuid, kind = "http_extended",
1471                        sql = %redact_sql_for_logging(query), num_params = params.len(),
1472                        "statement arrival"
1473                    );
1474                }
1475            }
1476        }
1477    }
1478
1479    // This API prohibits executing statements with responses whose
1480    // semantics are at odds with an HTTP response.
1481    fn check_prohibited_stmts<S: ResultSender>(
1482        sender: &S,
1483        stmt: &Statement<Raw>,
1484    ) -> Result<(), Error> {
1485        let kind: StatementKind = stmt.into();
1486        let execute_responses = Plan::generated_from(&kind)
1487            .into_iter()
1488            .map(ExecuteResponse::generated_from)
1489            .flatten()
1490            .collect::<Vec<_>>();
1491
1492        // Special-case `COPY TO` statements that are not `COPY ... TO STDOUT`, since
1493        // StatementKind::Copy links to several `ExecuteResponseKind`s that are not supported,
1494        // but this specific statement should be allowed.
1495        let is_valid_copy = matches!(
1496            stmt,
1497            Statement::Copy(CopyStatement {
1498                direction: CopyDirection::To,
1499                target: CopyTarget::Expr(_),
1500                ..
1501            }) | Statement::Copy(CopyStatement {
1502                direction: CopyDirection::From,
1503                target: CopyTarget::Expr(_),
1504                ..
1505            })
1506        );
1507
1508        if !is_valid_copy
1509            && execute_responses.iter().any(|execute_response| {
1510                // Returns true if a statement or execute response are unsupported.
1511                match execute_response {
1512                    ExecuteResponseKind::Subscribing if sender.allow_subscribe() => false,
1513                    ExecuteResponseKind::Fetch
1514                    | ExecuteResponseKind::Subscribing
1515                    | ExecuteResponseKind::CopyFrom
1516                    | ExecuteResponseKind::DeclaredCursor
1517                    | ExecuteResponseKind::ClosedCursor => true,
1518                    // Various statements generate `PeekPlan` (`SELECT`, `COPY`,
1519                    // `EXPLAIN`, `SHOW`) which has both `SendRows` and `CopyTo` as its
1520                    // possible response types. but `COPY` needs be picked out because
1521                    // http don't support its response type
1522                    ExecuteResponseKind::CopyTo if matches!(kind, StatementKind::Copy) => true,
1523                    _ => false,
1524                }
1525            })
1526        {
1527            return Err(Error::Unsupported(stmt.to_ast_string_simple()));
1528        }
1529        Ok(())
1530    }
1531
1532    fn parse<'a>(
1533        client: &SessionClient,
1534        query: &'a str,
1535    ) -> Result<Vec<StatementParseResult<'a>>, Error> {
1536        let result = client
1537            .parse(query)
1538            .map_err(|e| Error::Unstructured(anyhow!(e)))?;
1539        result.map_err(|e| AdapterError::from(e).into())
1540    }
1541
1542    let mut stmt_groups = vec![];
1543
1544    match request {
1545        SqlRequest::Simple { query } => match parse(client, query.as_str()) {
1546            Ok(stmts) => {
1547                let mut stmt_group = Vec::with_capacity(stmts.len());
1548                let mut stmt_err = None;
1549                for StatementParseResult { ast: stmt, sql } in stmts {
1550                    if let Err(err) = check_prohibited_stmts(sender, &stmt) {
1551                        stmt_err = Some(err);
1552                        break;
1553                    }
1554                    stmt_group.push((stmt, sql.to_string(), vec![]));
1555                }
1556                stmt_groups.push(stmt_err.map(Err).unwrap_or_else(|| Ok(stmt_group)));
1557            }
1558            Err(e) => stmt_groups.push(Err(e)),
1559        },
1560        SqlRequest::Extended { queries } => {
1561            for ExtendedRequest { query, params } in queries {
1562                match parse(client, &query) {
1563                    Ok(mut stmts) => {
1564                        if stmts.len() != 1 {
1565                            return Err(Error::Unstructured(anyhow!(
1566                                "each query must contain exactly 1 statement, but \"{}\" contains {}",
1567                                query,
1568                                stmts.len()
1569                            )));
1570                        }
1571
1572                        let StatementParseResult { ast: stmt, sql } = stmts.pop().unwrap();
1573                        stmt_groups.push(
1574                            check_prohibited_stmts(sender, &stmt)
1575                                .map(|_| vec![(stmt, sql.to_string(), params)]),
1576                        );
1577                    }
1578                    Err(e) => stmt_groups.push(Err(e)),
1579                };
1580            }
1581        }
1582    }
1583
1584    for stmt_group_res in stmt_groups {
1585        let executed = match stmt_group_res {
1586            Ok(stmt_group) => execute_stmt_group(client, sender, stmt_group).await,
1587            Err(e) => {
1588                let err = SqlResult::err(client, e);
1589                let _ = send_and_retire(err.into(), client, sender).await?;
1590                Ok(Err(()))
1591            }
1592        };
1593        // At the end of each group, commit implicit transactions. Do that here so that any `?`
1594        // early return can still be handled here.
1595        if client.session().transaction().is_implicit() {
1596            let ended = client.end_transaction(EndTransactionAction::Commit).await;
1597            if let Err(err) = ended {
1598                let err = SqlResult::err(client, err);
1599                let _ = send_and_retire(StatementResult::SqlResult(err), client, sender).await?;
1600            }
1601        }
1602        if executed?.is_err() {
1603            break;
1604        }
1605    }
1606
1607    Ok(())
1608}
1609
1610/// Executes a single statement in a [`SqlRequest`].
1611async fn execute_stmt<S: ResultSender>(
1612    client: &mut SessionClient,
1613    sender: &mut S,
1614    stmt: Statement<Raw>,
1615    sql: String,
1616    raw_params: Vec<Option<String>>,
1617) -> Result<StatementResult, Error> {
1618    const EMPTY_PORTAL: &str = "";
1619    if let Err(e) = client
1620        .prepare(EMPTY_PORTAL.into(), Some(stmt.clone()), sql, vec![])
1621        .await
1622    {
1623        return Ok(SqlResult::err(client, e).into());
1624    }
1625
1626    let prep_stmt = match client.get_prepared_statement(EMPTY_PORTAL).await {
1627        Ok(stmt) => stmt,
1628        Err(err) => {
1629            return Ok(SqlResult::err(client, err).into());
1630        }
1631    };
1632
1633    let param_types = &prep_stmt.desc().param_types;
1634    if param_types.len() != raw_params.len() {
1635        let message = anyhow!(
1636            "request supplied {actual} parameters, \
1637                        but {statement} requires {expected}",
1638            statement = stmt.to_ast_string_simple(),
1639            actual = raw_params.len(),
1640            expected = param_types.len()
1641        );
1642        return Ok(SqlResult::err(client, Error::Unstructured(message)).into());
1643    }
1644
1645    let buf = RowArena::new();
1646    let mut params = vec![];
1647    for (raw_param, mz_typ) in raw_params.into_iter().zip_eq(param_types) {
1648        let pg_typ = mz_pgrepr::Type::from(mz_typ);
1649        let datum = match raw_param {
1650            None => Datum::Null,
1651            Some(raw_param) => {
1652                match mz_pgrepr::Value::decode(
1653                    mz_pgwire_common::Format::Text,
1654                    &pg_typ,
1655                    raw_param.as_bytes(),
1656                ) {
1657                    Ok(param) => match param.into_datum_decode_error(&buf, &pg_typ, "parameter") {
1658                        Ok(datum) => datum,
1659                        Err(msg) => {
1660                            return Ok(
1661                                SqlResult::err(client, Error::Unstructured(anyhow!(msg))).into()
1662                            );
1663                        }
1664                    },
1665                    Err(err) => {
1666                        let msg = anyhow!("unable to decode parameter: {}", err);
1667                        return Ok(SqlResult::err(client, Error::Unstructured(msg)).into());
1668                    }
1669                }
1670            }
1671        };
1672        params.push((datum, mz_typ.clone()))
1673    }
1674
1675    let result_formats = vec![
1676        mz_pgwire_common::Format::Text;
1677        prep_stmt
1678            .desc()
1679            .relation_desc
1680            .clone()
1681            .map(|desc| desc.typ().column_types.len())
1682            .unwrap_or(0)
1683    ];
1684
1685    let desc = prep_stmt.desc().clone();
1686    let logging = Arc::clone(prep_stmt.logging());
1687    let stmt_ast = prep_stmt.stmt().cloned();
1688    let state_revision = prep_stmt.state_revision;
1689    if let Err(err) = client.session().set_portal(
1690        EMPTY_PORTAL.into(),
1691        desc,
1692        stmt_ast,
1693        logging,
1694        params,
1695        result_formats,
1696        state_revision,
1697    ) {
1698        return Ok(SqlResult::err(client, err).into());
1699    }
1700
1701    let desc = client
1702        .session()
1703        // We do not need to verify here because `client.execute` verifies below.
1704        .get_portal_unverified(EMPTY_PORTAL)
1705        .map(|portal| portal.desc.clone())
1706        .expect("unnamed portal should be present");
1707
1708    let res = client
1709        .execute(EMPTY_PORTAL.into(), futures::future::pending(), None)
1710        .await;
1711
1712    if S::SUPPORTS_STREAMING_NOTICES {
1713        sender
1714            .emit_streaming_notices(client.session().drain_notices())
1715            .await?;
1716    }
1717
1718    let (res, execute_started) = match res {
1719        Ok(res) => res,
1720        Err(e) => {
1721            return Ok(SqlResult::err(client, e).into());
1722        }
1723    };
1724    let tag = res.tag();
1725
1726    Ok(match res {
1727        ExecuteResponse::CreatedConnection { .. }
1728        | ExecuteResponse::CreatedDatabase { .. }
1729        | ExecuteResponse::CreatedSchema { .. }
1730        | ExecuteResponse::CreatedRole
1731        | ExecuteResponse::CreatedCluster { .. }
1732        | ExecuteResponse::CreatedClusterReplica { .. }
1733        | ExecuteResponse::CreatedTable { .. }
1734        | ExecuteResponse::CreatedIndex { .. }
1735        | ExecuteResponse::CreatedMetricSink { .. }
1736        | ExecuteResponse::CreatedIntrospectionSubscribe
1737        | ExecuteResponse::CreatedSecret { .. }
1738        | ExecuteResponse::CreatedSource { .. }
1739        | ExecuteResponse::CreatedSink { .. }
1740        | ExecuteResponse::CreatedView { .. }
1741        | ExecuteResponse::CreatedViews { .. }
1742        | ExecuteResponse::CreatedMaterializedView { .. }
1743        | ExecuteResponse::CreatedType
1744        | ExecuteResponse::CreatedNetworkPolicy
1745        | ExecuteResponse::Comment
1746        | ExecuteResponse::Deleted(_)
1747        | ExecuteResponse::DiscardedTemp
1748        | ExecuteResponse::DiscardedAll
1749        | ExecuteResponse::DroppedObject(_)
1750        | ExecuteResponse::DroppedOwned
1751        | ExecuteResponse::EmptyQuery
1752        | ExecuteResponse::GrantedPrivilege
1753        | ExecuteResponse::GrantedRole
1754        | ExecuteResponse::Inserted(_)
1755        | ExecuteResponse::Copied(_)
1756        | ExecuteResponse::Raised
1757        | ExecuteResponse::ReassignOwned
1758        | ExecuteResponse::RevokedPrivilege
1759        | ExecuteResponse::AlteredDefaultPrivileges
1760        | ExecuteResponse::RevokedRole
1761        | ExecuteResponse::StartedTransaction { .. }
1762        | ExecuteResponse::Updated(_)
1763        | ExecuteResponse::AlteredObject(_)
1764        | ExecuteResponse::AlteredRole
1765        | ExecuteResponse::AlteredSystemConfiguration
1766        | ExecuteResponse::Deallocate { .. }
1767        | ExecuteResponse::ValidatedConnection
1768        | ExecuteResponse::Prepare => SqlResult::ok(
1769            client,
1770            tag.expect("ok only called on tag-generating results"),
1771            Vec::default(),
1772        )
1773        .into(),
1774        ExecuteResponse::TransactionCommitted { params }
1775        | ExecuteResponse::TransactionRolledBack { params } => {
1776            let notify_set: mz_ore::collections::HashSet<_> = client
1777                .session()
1778                .vars()
1779                .notify_set()
1780                .map(|v| v.name().to_string())
1781                .collect();
1782            let params = params
1783                .into_iter()
1784                .filter(|(name, _value)| notify_set.contains(*name))
1785                .map(|(name, value)| ParameterStatus {
1786                    name: name.to_string(),
1787                    value,
1788                })
1789                .collect();
1790            SqlResult::ok(
1791                client,
1792                tag.expect("ok only called on tag-generating results"),
1793                params,
1794            )
1795            .into()
1796        }
1797        ExecuteResponse::SetVariable { name, .. } => {
1798            let mut params = Vec::with_capacity(1);
1799            if let Some(var) = client
1800                .session()
1801                .vars()
1802                .notify_set()
1803                .find(|v| v.name() == &name)
1804            {
1805                params.push(ParameterStatus {
1806                    name,
1807                    value: var.value(),
1808                });
1809            };
1810            SqlResult::ok(
1811                client,
1812                tag.expect("ok only called on tag-generating results"),
1813                params,
1814            )
1815            .into()
1816        }
1817        ExecuteResponse::SendingRowsStreaming {
1818            rows,
1819            instance_id,
1820            strategy,
1821        } => {
1822            let max_result_size =
1823                usize::cast_from(client.get_system_vars().await.max_result_size());
1824
1825            let rows_stream = RecordFirstRowStream::new(
1826                Box::new(rows),
1827                execute_started,
1828                client,
1829                Some(instance_id),
1830                Some(strategy),
1831            );
1832
1833            StatementResult::Rows {
1834                desc: desc.relation_desc.expect("RelationDesc must exist"),
1835                rows_stream,
1836                max_result_size,
1837            }
1838        }
1839        ExecuteResponse::SendingRowsImmediate { rows } => {
1840            let max_result_size =
1841                usize::cast_from(client.get_system_vars().await.max_result_size());
1842
1843            let rows = futures::stream::once(futures::future::ready(PeekResponseUnary::Rows(rows)));
1844            let rows_stream =
1845                RecordFirstRowStream::new(Box::new(rows), execute_started, client, None, None);
1846
1847            StatementResult::Rows {
1848                desc: desc.relation_desc.expect("RelationDesc must exist"),
1849                rows_stream,
1850                max_result_size,
1851            }
1852        }
1853        ExecuteResponse::Subscribing {
1854            rx,
1855            ctx_extra,
1856            instance_id,
1857        } => StatementResult::Subscribe {
1858            tag: "SUBSCRIBE".into(),
1859            desc: desc.relation_desc.unwrap(),
1860            rx: RecordFirstRowStream::new(rx, execute_started, client, Some(instance_id), None),
1861            ctx_extra,
1862        },
1863        res @ (ExecuteResponse::Fetch { .. }
1864        | ExecuteResponse::CopyTo { .. }
1865        | ExecuteResponse::CopyFrom { .. }
1866        | ExecuteResponse::DeclaredCursor
1867        | ExecuteResponse::ClosedCursor) => SqlResult::err(
1868            client,
1869            Error::Unstructured(anyhow!(
1870                "internal error: encountered prohibited ExecuteResponse {:?}.\n\n
1871            This is a bug. Can you please file an bug report letting us know?\n
1872            https://github.com/MaterializeInc/materialize/discussions/new?category=bug-reports",
1873                ExecuteResponseKind::from(res)
1874            )),
1875        )
1876        .into(),
1877    })
1878}
1879
1880fn make_notices(client: &mut SessionClient) -> Vec<Notice> {
1881    client
1882        .session()
1883        .drain_notices()
1884        .into_iter()
1885        .map(|notice| Notice {
1886            message: notice.to_string(),
1887            code: notice.code().code().to_string(),
1888            severity: notice.severity().as_str().to_lowercase(),
1889            detail: notice.detail(),
1890            hint: notice.hint(),
1891        })
1892        .collect()
1893}
1894
1895// Duplicated from protocol.rs.
1896// See postgres' backend/tcop/postgres.c IsTransactionExitStmt.
1897fn is_txn_exit_stmt(stmt: &Statement<Raw>) -> bool {
1898    matches!(
1899        stmt,
1900        Statement::Commit(_) | Statement::Rollback(_) | Statement::Prepare(_)
1901    )
1902}
1903
1904#[cfg(test)]
1905mod tests {
1906    use std::collections::BTreeMap;
1907
1908    use super::{Password, WebSocketAuth};
1909
1910    #[mz_ore::test]
1911    fn smoke_test_websocket_auth_parse() {
1912        struct TestCase {
1913            json: &'static str,
1914            expected: WebSocketAuth,
1915        }
1916
1917        let test_cases = vec![
1918            TestCase {
1919                json: r#"{ "user": "mz", "password": "1234" }"#,
1920                expected: WebSocketAuth::Basic {
1921                    user: "mz".to_string(),
1922                    password: Password("1234".to_string()),
1923                    options: BTreeMap::default(),
1924                },
1925            },
1926            TestCase {
1927                json: r#"{ "user": "mz", "password": "1234", "options": {} }"#,
1928                expected: WebSocketAuth::Basic {
1929                    user: "mz".to_string(),
1930                    password: Password("1234".to_string()),
1931                    options: BTreeMap::default(),
1932                },
1933            },
1934            TestCase {
1935                json: r#"{ "token": "i_am_a_token" }"#,
1936                expected: WebSocketAuth::Bearer {
1937                    token: "i_am_a_token".to_string(),
1938                    options: BTreeMap::default(),
1939                },
1940            },
1941            TestCase {
1942                json: r#"{ "token": "i_am_a_token", "options": { "foo": "bar" } }"#,
1943                expected: WebSocketAuth::Bearer {
1944                    token: "i_am_a_token".to_string(),
1945                    options: BTreeMap::from([("foo".to_string(), "bar".to_string())]),
1946                },
1947            },
1948        ];
1949
1950        fn assert_parse(json: &'static str, expected: WebSocketAuth) {
1951            let parsed: WebSocketAuth = serde_json::from_str(json).unwrap();
1952            assert_eq!(parsed, expected);
1953        }
1954
1955        for TestCase { json, expected } in test_cases {
1956            assert_parse(json, expected)
1957        }
1958    }
1959}