Skip to main content

mz_adapter/
command.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, BTreeSet};
11use std::net::IpAddr;
12use std::pin::Pin;
13use std::sync::Arc;
14use std::time::Duration;
15
16use chrono::{DateTime, Utc};
17use derivative::Derivative;
18use enum_kinds::EnumKind;
19use futures::Stream;
20use mz_adapter_types::connection::{ConnectionId, ConnectionIdType};
21use mz_auth::password::Password;
22use mz_cluster_client::ReplicaId;
23use mz_compute_types::ComputeInstanceId;
24use mz_controller_types::ClusterId;
25use mz_expr::RowSetFinishing;
26use mz_ore::collections::CollectionExt;
27use mz_ore::soft_assert_no_log;
28use mz_ore::tracing::OpenTelemetryContext;
29use mz_persist_client::PersistClient;
30use mz_pgcopy::CopyFormatParams;
31use mz_repr::global_id::TransientIdGen;
32use mz_repr::role_id::RoleId;
33use mz_repr::{CatalogItemId, ColumnIndex, Diff, GlobalId, Row, RowIterator, SqlRelationType};
34use mz_sql::ast::{FetchDirection, Raw, Statement};
35use mz_sql::catalog::ObjectType;
36use mz_sql::optimizer_metrics::OptimizerMetrics;
37use mz_sql::plan;
38use mz_sql::plan::{ExecuteTimeout, Plan, PlanKind, SideEffectingFunc};
39use mz_sql::session::user::User;
40use mz_sql::session::vars::{OwnedVarInput, SystemVars};
41use mz_sql_parser::ast::{AlterObjectRenameStatement, AlterOwnerStatement, DropObjectsStatement};
42use mz_storage_types::sources::Timeline;
43use mz_timestamp_oracle::TimestampOracle;
44use tokio::sync::{Semaphore, mpsc, oneshot, watch};
45use uuid::Uuid;
46
47use crate::active_compute_sink::ActiveSubscribeOwner;
48use crate::catalog::Catalog;
49use crate::config::{ScopedParameters, ScopedParametersScope, SystemParameterFrontend};
50use crate::coord::appends::{BuiltinTableAppendNotify, WriteResult};
51use crate::coord::consistency::CoordinatorInconsistencies;
52use crate::coord::peek::{PeekDataflowPlan, PeekResponseUnary};
53use crate::coord::timestamp_selection::TimestampDetermination;
54use crate::coord::{ExecuteContextExtra, ExecuteContextGuard};
55use crate::error::AdapterError;
56use crate::optimize::LirDataflowDescription;
57use crate::session::{EndTransactionAction, RowBatchStream, Session};
58use crate::statement_logging::{
59    StatementEndedExecutionReason, StatementExecutionStrategy, StatementLoggingFrontend,
60};
61use crate::statement_logging::{StatementLoggingId, WatchSetCreation};
62use crate::util::Transmittable;
63use crate::webhook::AppendWebhookResponse;
64use crate::{
65    AdapterNotice, AppendWebhookError, CollectionIdBundle, ReadHolds, TimestampExplanation,
66};
67
68/// A handle for pgwire to stream raw byte chunks to the coordinator's
69/// parallel background batch builder tasks during COPY FROM STDIN.
70#[derive(Debug)]
71pub struct CopyFromStdinWriter {
72    /// Channels for distributing raw byte chunks (split at row boundaries)
73    /// across parallel worker tasks. pgwire round-robins chunks across these.
74    pub batch_txs: Vec<mpsc::Sender<Vec<u8>>>,
75    /// Receives the final result (`Vec<ProtoBatch>` + total row count, or error)
76    /// from the collector task. pgwire uses this to commit the batches.
77    pub completion_rx: oneshot::Receiver<
78        Result<(Vec<mz_persist_client::batch::ProtoBatch>, u64), crate::AdapterError>,
79    >,
80}
81
82#[derive(Debug)]
83pub struct CatalogSnapshot {
84    pub catalog: Arc<Catalog>,
85}
86
87#[derive(Debug)]
88pub enum Command {
89    CatalogSnapshot {
90        tx: oneshot::Sender<CatalogSnapshot>,
91    },
92
93    Startup {
94        tx: oneshot::Sender<Result<StartupResponse, AdapterError>>,
95        user: User,
96        conn_id: ConnectionId,
97        client_ip: Option<IpAddr>,
98        secret_key: u32,
99        uuid: Uuid,
100        application_name: String,
101        notice_tx: mpsc::UnboundedSender<AdapterNotice>,
102    },
103
104    AuthenticatePassword {
105        tx: oneshot::Sender<Result<(), AdapterError>>,
106        role_name: String,
107        password: Option<Password>,
108    },
109
110    AuthenticateGetSASLChallenge {
111        tx: oneshot::Sender<Result<SASLChallengeResponse, AdapterError>>,
112        role_name: String,
113        nonce: String,
114    },
115
116    AuthenticateVerifySASLProof {
117        tx: oneshot::Sender<Result<SASLVerifyProofResponse, AdapterError>>,
118        role_name: String,
119        proof: String,
120        auth_message: String,
121        mock_hash: String,
122    },
123
124    CheckRoleCanLogin {
125        tx: oneshot::Sender<Result<(), AdapterError>>,
126        role_name: String,
127    },
128
129    Execute {
130        portal_name: String,
131        session: Session,
132        tx: oneshot::Sender<Response<ExecuteResponse>>,
133        /// The end-of-execution obligation of the statement this execution
134        /// serves, if any. `Coordinator::handle_execute` arms it again on
135        /// receipt. `None` means no log entry exists yet, so the coordinator
136        /// begins one.
137        outer_ctx_extra: Option<ExecuteContextExtra>,
138    },
139
140    /// Attempts to commit or abort the session's transaction. Guarantees that the Coordinator's
141    /// transaction state has been cleared, even if the commit or abort fails. (A failure can
142    /// happen, for example, if the session's role id has been dropped which will prevent
143    /// sequence_end_transaction from running.)
144    Commit {
145        action: EndTransactionAction,
146        session: Session,
147        tx: oneshot::Sender<Response<ExecuteResponse>>,
148    },
149
150    CancelRequest {
151        conn_id: ConnectionIdType,
152        secret_key: u32,
153    },
154
155    PrivilegedCancelRequest {
156        conn_id: ConnectionId,
157    },
158
159    GetWebhook {
160        database: String,
161        schema: String,
162        name: String,
163        tx: oneshot::Sender<Result<AppendWebhookResponse, AppendWebhookError>>,
164    },
165
166    GetSystemVars {
167        tx: oneshot::Sender<SystemVars>,
168    },
169
170    SetSystemVars {
171        vars: BTreeMap<String, String>,
172        conn_id: ConnectionId,
173        tx: oneshot::Sender<Result<(), AdapterError>>,
174    },
175
176    /// Replace the scoped feature-flag overrides (the complete desired state).
177    /// Computed by the system-parameter sync loop from continuous LaunchDarkly
178    /// evaluation. The coordinator stores this working copy and reconciles it
179    /// into the per-scope resolution boundaries (the compute controller's
180    /// per-replica dyncfg layer for `replica`-scoped parameters). See the
181    /// scoped feature flags design.
182    UpdateScopedSystemParameters {
183        overrides: ScopedParameters,
184        /// Bounds which objects' durable rows the reconcile may prune. See
185        /// [`crate::catalog::Op::UpdateScopedSystemParameters`].
186        prune_scope: ScopedParametersScope,
187        tx: oneshot::Sender<()>,
188    },
189
190    /// Install (or replace) the shared system-parameter frontend on the
191    /// coordinator, so catalog transactions can resolve a new object's scoped
192    /// overrides before its replica is provisioned or its first dataflow is
193    /// planned, rather than waiting for the next sync tick. Sent by the sync loop
194    /// whenever it (re)initializes the frontend. See the scoped feature flags
195    /// design.
196    InstallScopedSystemParameterFrontend {
197        frontend: Arc<SystemParameterFrontend>,
198    },
199
200    InjectAuditEvents {
201        events: Vec<crate::catalog::InjectedAuditEvent>,
202        conn_id: ConnectionId,
203        tx: oneshot::Sender<Result<(), AdapterError>>,
204    },
205
206    Terminate {
207        conn_id: ConnectionId,
208        tx: Option<oneshot::Sender<Result<(), AdapterError>>>,
209    },
210
211    /// Sets up a streaming COPY FROM STDIN operation. The coordinator
212    /// creates parallel background batch builder tasks and returns a
213    /// [`CopyFromStdinWriter`] that pgwire uses to stream raw byte chunks.
214    StartCopyFromStdin {
215        target_id: CatalogItemId,
216        target_name: String,
217        columns: Vec<ColumnIndex>,
218        /// The row description for the target table (used for constraint checks).
219        row_desc: mz_repr::RelationDesc,
220        /// Copy format parameters (text/csv/binary) for decoding raw bytes.
221        params: mz_pgcopy::CopyFormatParams<'static>,
222        session: Session,
223        tx: oneshot::Sender<Response<CopyFromStdinWriter>>,
224    },
225
226    /// Performs any cleanup and logging actions necessary for
227    /// finalizing a statement execution.
228    ///
229    /// Only used for cases that terminate in the protocol layer and
230    /// otherwise have no reason to hand control back to the coordinator.
231    /// In other cases, we piggy-back on another command.
232    RetireExecute {
233        data: ExecuteContextExtra,
234        reason: StatementEndedExecutionReason,
235    },
236
237    CheckConsistency {
238        tx: oneshot::Sender<Result<(), CoordinatorInconsistencies>>,
239    },
240
241    Dump {
242        tx: oneshot::Sender<Result<serde_json::Value, anyhow::Error>>,
243    },
244
245    GetComputeInstanceClient {
246        instance_id: ComputeInstanceId,
247        tx: oneshot::Sender<
248            Result<
249                mz_compute_client::controller::instance_client::InstanceClient,
250                mz_compute_client::controller::error::InstanceMissing,
251            >,
252        >,
253    },
254
255    GetOracle {
256        timeline: Timeline,
257        tx: oneshot::Sender<
258            Result<Arc<dyn TimestampOracle<mz_repr::Timestamp> + Send + Sync>, AdapterError>,
259        >,
260    },
261
262    DetermineRealTimeRecentTimestamp {
263        source_ids: BTreeSet<GlobalId>,
264        real_time_recency_timeout: Duration,
265        tx: oneshot::Sender<Result<Option<mz_repr::Timestamp>, AdapterError>>,
266    },
267
268    GetTransactionReadHoldsBundle {
269        conn_id: ConnectionId,
270        tx: oneshot::Sender<Option<ReadHolds>>,
271    },
272
273    /// _Merges_ the given read holds into the given connection's stored transaction read holds.
274    StoreTransactionReadHolds {
275        conn_id: ConnectionId,
276        read_holds: ReadHolds,
277        tx: oneshot::Sender<()>,
278    },
279
280    ExecuteSlowPathPeek {
281        peek: crate::peek_client::PeekHandle,
282        dataflow_plan: Box<PeekDataflowPlan>,
283        determination: TimestampDetermination,
284        finishing: RowSetFinishing,
285        compute_instance: ComputeInstanceId,
286        target_replica: Option<ReplicaId>,
287        intermediate_result_type: SqlRelationType,
288        conn_id: ConnectionId,
289        max_result_size: u64,
290        max_query_result_size: Option<u64>,
291        /// If statement logging is enabled, contains all info needed for installing watch sets
292        /// and logging the statement execution.
293        watch_set: Option<WatchSetCreation>,
294        tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
295    },
296
297    ExecuteSubscribe {
298        df_desc: mz_compute_types::dataflows::LirDataflowDescription,
299        dependency_ids: BTreeSet<GlobalId>,
300        cluster_id: ComputeInstanceId,
301        replica_id: Option<ReplicaId>,
302        conn_id: ConnectionId,
303        session_uuid: Uuid,
304        read_holds: ReadHolds,
305        plan: plan::SubscribePlan,
306        statement_logging_id: Option<StatementLoggingId>,
307        tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
308    },
309
310    /// Preflight check for COPY TO S3 operation. This runs the slow S3 operations
311    /// (loading SDK config, checking bucket path, verifying permissions, uploading sentinel)
312    /// in a background task to avoid blocking the coordinator.
313    CopyToPreflight {
314        /// The S3 connection info needed for preflight checks.
315        s3_sink_connection: mz_compute_types::sinks::CopyToS3OneshotSinkConnection,
316        /// The sink ID for logging and S3 key management.
317        sink_id: GlobalId,
318        /// Response channel for the preflight result.
319        tx: oneshot::Sender<Result<(), AdapterError>>,
320    },
321
322    ExecuteCopyTo {
323        df_desc: Box<mz_compute_types::dataflows::LirDataflowDescription>,
324        compute_instance: ComputeInstanceId,
325        target_replica: Option<ReplicaId>,
326        source_ids: BTreeSet<GlobalId>,
327        conn_id: ConnectionId,
328        /// If statement logging is enabled, contains all info needed for installing watch sets
329        /// and logging the statement execution.
330        watch_set: Option<WatchSetCreation>,
331        tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
332    },
333
334    /// Execute a side-effecting function from the frontend peek path.
335    ExecuteSideEffectingFunc {
336        plan: SideEffectingFunc,
337        conn_id: ConnectionId,
338        tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
339    },
340
341    /// Look up an active connection by its raw connection ID, returning its
342    /// `ConnectionId` handle and authenticated role, or `None` if there is no
343    /// such connection.
344    ///
345    /// While the caller holds the returned `ConnectionId` handle, the raw
346    /// connection ID cannot be reused by a new connection. Frontend peek
347    /// sequencing relies on this to ensure that the connection it performs an
348    /// RBAC check against is the same one that a subsequent
349    /// `ExecuteSideEffectingFunc` acts on.
350    LookupConnection {
351        connection_id: u32,
352        tx: oneshot::Sender<Option<(ConnectionId, RoleId)>>,
353    },
354
355    /// Installs dependency watches for a sampled frontend peek.
356    InstallPeekWatchSets {
357        conn_id: ConnectionId,
358        watch_set: WatchSetCreation,
359        tx: oneshot::Sender<Result<(), AdapterError>>,
360    },
361
362    /// Generate a timestamp explanation, or fail with `ConcurrentDependencyDrop`
363    /// if a collection in `id_bundle` no longer exists.
364    /// This is used when `emit_timestamp_notice` is enabled.
365    ExplainTimestamp {
366        conn_id: ConnectionId,
367        session_wall_time: DateTime<Utc>,
368        cluster_id: ClusterId,
369        id_bundle: CollectionIdBundle,
370        determination: TimestampDetermination,
371        tx: oneshot::Sender<Result<TimestampExplanation, AdapterError>>,
372    },
373
374    /// Registers a connection-scoped cancellation watch and returns a receiver
375    /// that becomes `true` when cancellation is requested for the connection.
376    ///
377    /// Registration always installs a fresh channel, so the caller cannot
378    /// observe a cancellation aimed at an earlier statement.
379    RegisterConnectionCancelWatch {
380        conn_id: ConnectionId,
381        tx: oneshot::Sender<watch::Receiver<bool>>,
382    },
383
384    /// Creates an internal subscribe, meaning one that writes no
385    /// `mz_subscriptions` row, and returns the response channel. Used by
386    /// frontend-sequenced read-then-write (DELETE/UPDATE/INSERT...SELECT)
387    /// operations via OCC.
388    CreateInternalSubscribe {
389        df_desc: Box<LirDataflowDescription>,
390        cluster_id: ComputeInstanceId,
391        replica_id: Option<ReplicaId>,
392        depends_on: BTreeSet<GlobalId>,
393        as_of: mz_repr::Timestamp,
394        arity: usize,
395        sink_id: GlobalId,
396        owner: ActiveSubscribeOwner,
397        start_time: mz_ore::now::EpochMillis,
398        read_holds: ReadHolds,
399        tx: oneshot::Sender<Result<mpsc::UnboundedReceiver<PeekResponseUnary>, AdapterError>>,
400    },
401
402    /// Submits a write attempt. Carries the accumulated diffs to write.
403    ///
404    /// `write_ts` selects between two modes:
405    /// - `Some(ts)`: the write must land at exactly `ts`, and reports
406    ///   `WriteResult::TimestampPassed` if the table's timestamp is already past
407    ///   it. The caller decides whether to recompute the diffs and try again.
408    /// - `None`: the coordinator picks the timestamp from the oracle during
409    ///   group commit, so the timestamp cannot be passed. Every other outcome,
410    ///   including read-only, a changed target and cancellation, is reported the
411    ///   same way in both modes.
412    AttemptWrite {
413        attempt: WriteAttemptKind,
414        target_id: CatalogItemId,
415        target_global_id: GlobalId,
416        diffs: Vec<(Row, Diff)>,
417        tx: oneshot::Sender<WriteResult>,
418    },
419
420    /// Drops an internal subscribe. Fire-and-forget, the caller does not wait
421    /// for completion.
422    DropInternalSubscribe {
423        sink_id: GlobalId,
424    },
425}
426
427/// Who a read-then-write commits on behalf of, and how its timestamp is chosen.
428///
429/// Group commit picking the timestamp requires a connection to answer through,
430/// so that combination is only reachable from a session.
431#[derive(Debug)]
432pub enum WriteAttemptKind {
433    /// A session's write, cancelled with `conn_id` if the connection goes away
434    /// before it commits. A `write_ts` of `None` lets group commit pick the
435    /// timestamp, which then cannot be reported as passed.
436    Session {
437        conn_id: ConnectionId,
438        write_ts: Option<mz_repr::Timestamp>,
439    },
440    /// Coordinator background work. There is no connection to cancel with, so
441    /// the caller names the timestamp and handles `TimestampPassed` itself.
442    Background { write_ts: mz_repr::Timestamp },
443}
444
445impl Command {
446    pub fn session(&self) -> Option<&Session> {
447        match self {
448            Command::Execute { session, .. }
449            | Command::Commit { session, .. }
450            | Command::StartCopyFromStdin { session, .. } => Some(session),
451            Command::CancelRequest { .. }
452            | Command::Startup { .. }
453            | Command::AuthenticatePassword { .. }
454            | Command::AuthenticateGetSASLChallenge { .. }
455            | Command::AuthenticateVerifySASLProof { .. }
456            | Command::CheckRoleCanLogin { .. }
457            | Command::CatalogSnapshot { .. }
458            | Command::PrivilegedCancelRequest { .. }
459            | Command::GetWebhook { .. }
460            | Command::Terminate { .. }
461            | Command::GetSystemVars { .. }
462            | Command::SetSystemVars { .. }
463            | Command::UpdateScopedSystemParameters { .. }
464            | Command::InstallScopedSystemParameterFrontend { .. }
465            | Command::RetireExecute { .. }
466            | Command::CheckConsistency { .. }
467            | Command::Dump { .. }
468            | Command::GetComputeInstanceClient { .. }
469            | Command::GetOracle { .. }
470            | Command::DetermineRealTimeRecentTimestamp { .. }
471            | Command::GetTransactionReadHoldsBundle { .. }
472            | Command::StoreTransactionReadHolds { .. }
473            | Command::ExecuteSlowPathPeek { .. }
474            | Command::ExecuteSubscribe { .. }
475            | Command::CopyToPreflight { .. }
476            | Command::ExecuteCopyTo { .. }
477            | Command::ExecuteSideEffectingFunc { .. }
478            | Command::LookupConnection { .. }
479            | Command::InstallPeekWatchSets { .. }
480            | Command::ExplainTimestamp { .. }
481            | Command::InjectAuditEvents { .. }
482            | Command::RegisterConnectionCancelWatch { .. }
483            | Command::CreateInternalSubscribe { .. }
484            | Command::AttemptWrite { .. }
485            | Command::DropInternalSubscribe { .. } => None,
486        }
487    }
488
489    pub fn session_mut(&mut self) -> Option<&mut Session> {
490        match self {
491            Command::Execute { session, .. }
492            | Command::Commit { session, .. }
493            | Command::StartCopyFromStdin { session, .. } => Some(session),
494            Command::CancelRequest { .. }
495            | Command::Startup { .. }
496            | Command::AuthenticatePassword { .. }
497            | Command::AuthenticateGetSASLChallenge { .. }
498            | Command::AuthenticateVerifySASLProof { .. }
499            | Command::CheckRoleCanLogin { .. }
500            | Command::CatalogSnapshot { .. }
501            | Command::PrivilegedCancelRequest { .. }
502            | Command::GetWebhook { .. }
503            | Command::Terminate { .. }
504            | Command::GetSystemVars { .. }
505            | Command::SetSystemVars { .. }
506            | Command::UpdateScopedSystemParameters { .. }
507            | Command::InstallScopedSystemParameterFrontend { .. }
508            | Command::RetireExecute { .. }
509            | Command::CheckConsistency { .. }
510            | Command::Dump { .. }
511            | Command::GetComputeInstanceClient { .. }
512            | Command::GetOracle { .. }
513            | Command::DetermineRealTimeRecentTimestamp { .. }
514            | Command::GetTransactionReadHoldsBundle { .. }
515            | Command::StoreTransactionReadHolds { .. }
516            | Command::ExecuteSlowPathPeek { .. }
517            | Command::ExecuteSubscribe { .. }
518            | Command::CopyToPreflight { .. }
519            | Command::ExecuteCopyTo { .. }
520            | Command::ExecuteSideEffectingFunc { .. }
521            | Command::LookupConnection { .. }
522            | Command::InstallPeekWatchSets { .. }
523            | Command::ExplainTimestamp { .. }
524            | Command::InjectAuditEvents { .. }
525            | Command::RegisterConnectionCancelWatch { .. }
526            | Command::CreateInternalSubscribe { .. }
527            | Command::AttemptWrite { .. }
528            | Command::DropInternalSubscribe { .. } => None,
529        }
530    }
531}
532
533#[derive(Debug)]
534pub struct Response<T> {
535    pub result: Result<T, AdapterError>,
536    pub session: Session,
537    pub otel_ctx: OpenTelemetryContext,
538}
539
540#[derive(Debug, Clone, Copy)]
541pub struct SuperuserAttribute(pub Option<bool>);
542
543/// The response to [`Client::startup`](crate::Client::startup).
544#[derive(Derivative)]
545#[derivative(Debug)]
546pub struct StartupResponse {
547    pub(crate) connection_peeks: Arc<crate::peek_registry::ConnectionPeeks>,
548    /// Cancellation notifications for session-owned completion waits.
549    pub frontend_cancel_rx: tokio::sync::watch::Receiver<()>,
550    /// RoleId for the user.
551    pub role_id: RoleId,
552    /// The role's superuser attribute in the Catalog.
553    /// This attribute is None for Cloud. Cloud is able
554    /// to derive the role's superuser status from
555    /// external_metadata_rx.
556    pub superuser_attribute: SuperuserAttribute,
557    /// A future that completes when all necessary Builtin Table writes have completed.
558    #[derivative(Debug = "ignore")]
559    pub write_notify: BuiltinTableAppendNotify,
560    /// Map of (name, VarInput::Flat) tuples of session default variables that should be set.
561    pub session_defaults: BTreeMap<String, OwnedVarInput>,
562    pub catalog: Arc<Catalog>,
563    pub storage_collections:
564        Arc<dyn mz_storage_client::storage_collections::StorageCollections + Send + Sync>,
565    pub transient_id_gen: Arc<TransientIdGen>,
566    pub optimizer_metrics: OptimizerMetrics,
567    pub persist_client: PersistClient,
568    pub statement_logging_frontend: StatementLoggingFrontend,
569    /// Semaphore for limiting concurrent OCC (optimistic concurrency control)
570    /// write operations.
571    pub occ_write_semaphore: Arc<Semaphore>,
572    /// Requests a group commit, which is how the frontend asks for the write
573    /// timeline to advance without having anything to write.
574    pub group_commit_notifier: crate::coord::appends::GroupCommitNotifier,
575    /// Whether the coordinator is in read-only mode (e.g. during 0dt upgrades).
576    /// The frontend path must reject mutations when this is true.
577    pub read_only: bool,
578}
579
580#[derive(Derivative)]
581#[derivative(Debug)]
582pub struct SASLChallengeResponse {
583    pub iteration_count: usize,
584    /// Base64-encoded salt for the SASL challenge.
585    pub salt: String,
586    pub nonce: String,
587}
588
589#[derive(Derivative)]
590#[derivative(Debug)]
591pub struct SASLVerifyProofResponse {
592    pub verifier: String,
593}
594
595// Facile implementation for `StartupResponse`, which does not use the `allowed`
596// feature of `ClientTransmitter`.
597impl Transmittable for StartupResponse {
598    type Allowed = bool;
599    fn to_allowed(&self) -> Self::Allowed {
600        true
601    }
602}
603
604/// The response to [`SessionClient::dump_catalog`](crate::SessionClient::dump_catalog).
605#[derive(Debug, Clone)]
606pub struct CatalogDump(String);
607
608impl CatalogDump {
609    pub fn new(raw: String) -> Self {
610        CatalogDump(raw)
611    }
612
613    pub fn into_string(self) -> String {
614        self.0
615    }
616}
617
618impl Transmittable for CatalogDump {
619    type Allowed = bool;
620    fn to_allowed(&self) -> Self::Allowed {
621        true
622    }
623}
624
625impl Transmittable for SystemVars {
626    type Allowed = bool;
627    fn to_allowed(&self) -> Self::Allowed {
628        true
629    }
630}
631
632/// The response to [`SessionClient::execute`](crate::SessionClient::execute).
633#[derive(EnumKind, Derivative)]
634#[derivative(Debug)]
635#[enum_kind(ExecuteResponseKind, derive(PartialOrd, Ord))]
636pub enum ExecuteResponse {
637    /// The default privileges were altered.
638    AlteredDefaultPrivileges,
639    /// The requested object was altered.
640    AlteredObject(ObjectType),
641    /// The role was altered.
642    AlteredRole,
643    /// The system configuration was altered.
644    AlteredSystemConfiguration,
645    /// The requested cursor was closed.
646    ClosedCursor,
647    /// The provided comment was created.
648    Comment,
649    /// The specified number of rows were copied into the requested output.
650    Copied(usize),
651    /// The response for a COPY TO STDOUT query.
652    CopyTo {
653        format: mz_sql::plan::CopyFormat,
654        resp: Box<ExecuteResponse>,
655    },
656    CopyFrom {
657        /// Table we're copying into.
658        target_id: CatalogItemId,
659        /// Human-readable full name of the target table.
660        target_name: String,
661        columns: Vec<ColumnIndex>,
662        params: CopyFormatParams<'static>,
663        ctx_extra: ExecuteContextGuard,
664    },
665    /// The requested connection was created.
666    CreatedConnection,
667    /// The requested database was created.
668    CreatedDatabase,
669    /// The requested schema was created.
670    CreatedSchema,
671    /// The requested role was created.
672    CreatedRole,
673    /// The requested cluster was created.
674    CreatedCluster,
675    /// The requested cluster replica was created.
676    CreatedClusterReplica,
677    /// The requested index was created.
678    CreatedIndex,
679    /// The requested metric sink was created.
680    CreatedMetricSink,
681    /// The requested introspection subscribe was created.
682    CreatedIntrospectionSubscribe,
683    /// The requested secret was created.
684    CreatedSecret,
685    /// The requested sink was created.
686    CreatedSink,
687    /// The requested source was created.
688    CreatedSource,
689    /// The requested table was created.
690    CreatedTable,
691    /// The requested view was created.
692    CreatedView,
693    /// The requested views were created.
694    CreatedViews,
695    /// The requested materialized view was created.
696    CreatedMaterializedView,
697    /// The requested type was created.
698    CreatedType,
699    /// The requested network policy was created.
700    CreatedNetworkPolicy,
701    /// The requested query policy was created.
702    CreatedQueryPolicy,
703    /// The requested prepared statement was removed.
704    Deallocate { all: bool },
705    /// The requested cursor was declared.
706    DeclaredCursor,
707    /// The specified number of rows were deleted from the requested table.
708    Deleted(usize),
709    /// The temporary objects associated with the session have been discarded.
710    DiscardedTemp,
711    /// All state associated with the session has been discarded.
712    DiscardedAll {
713        /// Session parameters that changed because the session was reset.
714        params: BTreeMap<&'static str, String>,
715    },
716    /// The requested object was dropped.
717    DroppedObject(ObjectType),
718    /// The requested objects were dropped.
719    DroppedOwned,
720    /// The provided query was empty.
721    EmptyQuery,
722    /// Fetch results from a cursor.
723    Fetch {
724        /// The name of the cursor from which to fetch results.
725        name: String,
726        /// The number of results to fetch.
727        count: Option<FetchDirection>,
728        /// How long to wait for results to arrive.
729        timeout: ExecuteTimeout,
730        ctx_extra: ExecuteContextGuard,
731    },
732    /// The requested privilege was granted.
733    GrantedPrivilege,
734    /// The requested role was granted.
735    GrantedRole,
736    /// The specified number of rows were inserted into the requested table.
737    Inserted(usize),
738    /// The specified prepared statement was created.
739    Prepare,
740    /// A user-requested warning was raised.
741    Raised,
742    /// The requested objects were reassigned.
743    ReassignOwned,
744    /// The requested privilege was revoked.
745    RevokedPrivilege,
746    /// The requested role was revoked.
747    RevokedRole,
748    /// Rows will be delivered via the specified stream.
749    SendingRowsStreaming {
750        #[derivative(Debug = "ignore")]
751        rows: Pin<Box<dyn Stream<Item = PeekResponseUnary> + Send + Sync>>,
752        instance_id: ComputeInstanceId,
753        strategy: StatementExecutionStrategy,
754    },
755    /// Rows are known to be available immediately, and thus the execution is
756    /// considered ended in the coordinator.
757    SendingRowsImmediate {
758        #[derivative(Debug = "ignore")]
759        rows: Box<dyn RowIterator + Send + Sync>,
760    },
761    /// The specified variable was set to a new value.
762    SetVariable {
763        name: String,
764        /// Whether the operation was a `RESET` rather than a set.
765        reset: bool,
766    },
767    /// A new transaction was started.
768    StartedTransaction,
769    /// Updates to the requested source or view will be streamed to the
770    /// contained receiver.
771    Subscribing {
772        #[derivative(Debug = "ignore")]
773        rx: RowBatchStream,
774        ctx_extra: ExecuteContextGuard,
775        instance_id: ComputeInstanceId,
776    },
777    /// The active transaction committed.
778    TransactionCommitted {
779        /// Session parameters that changed because the transaction ended.
780        params: BTreeMap<&'static str, String>,
781    },
782    /// The active transaction rolled back.
783    TransactionRolledBack {
784        /// Session parameters that changed because the transaction ended.
785        params: BTreeMap<&'static str, String>,
786    },
787    /// The specified number of rows were updated in the requested table.
788    Updated(usize),
789    /// A connection was validated.
790    ValidatedConnection,
791}
792
793impl TryFrom<&Statement<Raw>> for ExecuteResponse {
794    type Error = ();
795
796    /// Returns Ok if this Statement always produces a single, trivial ExecuteResponse.
797    fn try_from(stmt: &Statement<Raw>) -> Result<Self, Self::Error> {
798        let resp_kinds = Plan::generated_from(&stmt.into())
799            .iter()
800            .map(ExecuteResponse::generated_from)
801            .flatten()
802            .cloned()
803            .collect::<BTreeSet<ExecuteResponseKind>>();
804        let resps = resp_kinds
805            .iter()
806            .map(|r| (*r).try_into())
807            .collect::<Result<Vec<ExecuteResponse>, _>>();
808        // Check if this statement's possible plans yield exactly one possible ExecuteResponse.
809        if let Ok(resps) = resps {
810            if resps.len() == 1 {
811                return Ok(resps.into_element());
812            }
813        }
814        let resp = match stmt {
815            Statement::DropObjects(DropObjectsStatement { object_type, .. }) => {
816                ExecuteResponse::DroppedObject((*object_type).into())
817            }
818            Statement::AlterObjectRename(AlterObjectRenameStatement { object_type, .. })
819            | Statement::AlterOwner(AlterOwnerStatement { object_type, .. }) => {
820                ExecuteResponse::AlteredObject((*object_type).into())
821            }
822            _ => return Err(()),
823        };
824        // Ensure that if the planner ever adds possible plans we complain here.
825        soft_assert_no_log!(
826            resp_kinds.len() == 1
827                && resp_kinds.first().expect("must exist") == &ExecuteResponseKind::from(&resp),
828            "ExecuteResponses out of sync with planner"
829        );
830        Ok(resp)
831    }
832}
833
834impl TryInto<ExecuteResponse> for ExecuteResponseKind {
835    type Error = ();
836
837    /// Attempts to convert into an ExecuteResponse. Returns an error if not possible without
838    /// actually executing a statement.
839    fn try_into(self) -> Result<ExecuteResponse, Self::Error> {
840        match self {
841            ExecuteResponseKind::AlteredDefaultPrivileges => {
842                Ok(ExecuteResponse::AlteredDefaultPrivileges)
843            }
844            ExecuteResponseKind::AlteredObject => Err(()),
845            ExecuteResponseKind::AlteredRole => Ok(ExecuteResponse::AlteredRole),
846            ExecuteResponseKind::AlteredSystemConfiguration => {
847                Ok(ExecuteResponse::AlteredSystemConfiguration)
848            }
849            ExecuteResponseKind::ClosedCursor => Ok(ExecuteResponse::ClosedCursor),
850            ExecuteResponseKind::Comment => Ok(ExecuteResponse::Comment),
851            ExecuteResponseKind::Copied => Err(()),
852            ExecuteResponseKind::CopyTo => Err(()),
853            ExecuteResponseKind::CopyFrom => Err(()),
854            ExecuteResponseKind::CreatedConnection => Ok(ExecuteResponse::CreatedConnection),
855            ExecuteResponseKind::CreatedDatabase => Ok(ExecuteResponse::CreatedDatabase),
856            ExecuteResponseKind::CreatedSchema => Ok(ExecuteResponse::CreatedSchema),
857            ExecuteResponseKind::CreatedRole => Ok(ExecuteResponse::CreatedRole),
858            ExecuteResponseKind::CreatedCluster => Ok(ExecuteResponse::CreatedCluster),
859            ExecuteResponseKind::CreatedClusterReplica => {
860                Ok(ExecuteResponse::CreatedClusterReplica)
861            }
862            ExecuteResponseKind::CreatedIndex => Ok(ExecuteResponse::CreatedIndex),
863            ExecuteResponseKind::CreatedMetricSink => Ok(ExecuteResponse::CreatedMetricSink),
864            ExecuteResponseKind::CreatedSecret => Ok(ExecuteResponse::CreatedSecret),
865            ExecuteResponseKind::CreatedSink => Ok(ExecuteResponse::CreatedSink),
866            ExecuteResponseKind::CreatedSource => Ok(ExecuteResponse::CreatedSource),
867            ExecuteResponseKind::CreatedTable => Ok(ExecuteResponse::CreatedTable),
868            ExecuteResponseKind::CreatedView => Ok(ExecuteResponse::CreatedView),
869            ExecuteResponseKind::CreatedViews => Ok(ExecuteResponse::CreatedViews),
870            ExecuteResponseKind::CreatedMaterializedView => {
871                Ok(ExecuteResponse::CreatedMaterializedView)
872            }
873            ExecuteResponseKind::CreatedNetworkPolicy => Ok(ExecuteResponse::CreatedNetworkPolicy),
874            ExecuteResponseKind::CreatedQueryPolicy => Ok(ExecuteResponse::CreatedQueryPolicy),
875            ExecuteResponseKind::CreatedType => Ok(ExecuteResponse::CreatedType),
876            ExecuteResponseKind::Deallocate => Err(()),
877            ExecuteResponseKind::DeclaredCursor => Ok(ExecuteResponse::DeclaredCursor),
878            ExecuteResponseKind::Deleted => Err(()),
879            ExecuteResponseKind::DiscardedTemp => Ok(ExecuteResponse::DiscardedTemp),
880            ExecuteResponseKind::DiscardedAll => Err(()),
881            ExecuteResponseKind::DroppedObject => Err(()),
882            ExecuteResponseKind::DroppedOwned => Ok(ExecuteResponse::DroppedOwned),
883            ExecuteResponseKind::EmptyQuery => Ok(ExecuteResponse::EmptyQuery),
884            ExecuteResponseKind::Fetch => Err(()),
885            ExecuteResponseKind::GrantedPrivilege => Ok(ExecuteResponse::GrantedPrivilege),
886            ExecuteResponseKind::GrantedRole => Ok(ExecuteResponse::GrantedRole),
887            ExecuteResponseKind::Inserted => Err(()),
888            ExecuteResponseKind::Prepare => Ok(ExecuteResponse::Prepare),
889            ExecuteResponseKind::Raised => Ok(ExecuteResponse::Raised),
890            ExecuteResponseKind::ReassignOwned => Ok(ExecuteResponse::ReassignOwned),
891            ExecuteResponseKind::RevokedPrivilege => Ok(ExecuteResponse::RevokedPrivilege),
892            ExecuteResponseKind::RevokedRole => Ok(ExecuteResponse::RevokedRole),
893            ExecuteResponseKind::SetVariable => Err(()),
894            ExecuteResponseKind::StartedTransaction => Ok(ExecuteResponse::StartedTransaction),
895            ExecuteResponseKind::Subscribing => Err(()),
896            ExecuteResponseKind::TransactionCommitted => Err(()),
897            ExecuteResponseKind::TransactionRolledBack => Err(()),
898            ExecuteResponseKind::Updated => Err(()),
899            ExecuteResponseKind::ValidatedConnection => Ok(ExecuteResponse::ValidatedConnection),
900            ExecuteResponseKind::SendingRowsStreaming => Err(()),
901            ExecuteResponseKind::SendingRowsImmediate => Err(()),
902            ExecuteResponseKind::CreatedIntrospectionSubscribe => {
903                Ok(ExecuteResponse::CreatedIntrospectionSubscribe)
904            }
905        }
906    }
907}
908
909impl ExecuteResponse {
910    pub fn tag(&self) -> Option<String> {
911        use ExecuteResponse::*;
912        match self {
913            AlteredDefaultPrivileges => Some("ALTER DEFAULT PRIVILEGES".into()),
914            AlteredObject(o) => Some(format!("ALTER {}", o)),
915            AlteredRole => Some("ALTER ROLE".into()),
916            AlteredSystemConfiguration => Some("ALTER SYSTEM".into()),
917            ClosedCursor => Some("CLOSE CURSOR".into()),
918            Comment => Some("COMMENT".into()),
919            Copied(n) => Some(format!("COPY {}", n)),
920            CopyTo { .. } => None,
921            CopyFrom { .. } => None,
922            CreatedConnection { .. } => Some("CREATE CONNECTION".into()),
923            CreatedDatabase { .. } => Some("CREATE DATABASE".into()),
924            CreatedSchema { .. } => Some("CREATE SCHEMA".into()),
925            CreatedRole => Some("CREATE ROLE".into()),
926            CreatedCluster { .. } => Some("CREATE CLUSTER".into()),
927            CreatedClusterReplica { .. } => Some("CREATE CLUSTER REPLICA".into()),
928            CreatedIndex { .. } => Some("CREATE INDEX".into()),
929            CreatedMetricSink { .. } => Some("CREATE METRIC SINK".into()),
930            CreatedSecret { .. } => Some("CREATE SECRET".into()),
931            CreatedSink { .. } => Some("CREATE SINK".into()),
932            CreatedSource { .. } => Some("CREATE SOURCE".into()),
933            CreatedTable { .. } => Some("CREATE TABLE".into()),
934            CreatedView { .. } => Some("CREATE VIEW".into()),
935            CreatedViews { .. } => Some("CREATE VIEWS".into()),
936            CreatedMaterializedView { .. } => Some("CREATE MATERIALIZED VIEW".into()),
937            CreatedType => Some("CREATE TYPE".into()),
938            CreatedNetworkPolicy => Some("CREATE NETWORKPOLICY".into()),
939            CreatedQueryPolicy => Some("CREATE QUERY POLICY".into()),
940            Deallocate { all } => Some(format!("DEALLOCATE{}", if *all { " ALL" } else { "" })),
941            DeclaredCursor => Some("DECLARE CURSOR".into()),
942            Deleted(n) => Some(format!("DELETE {}", n)),
943            DiscardedTemp => Some("DISCARD TEMP".into()),
944            DiscardedAll { .. } => Some("DISCARD ALL".into()),
945            DroppedObject(o) => Some(format!("DROP {o}")),
946            DroppedOwned => Some("DROP OWNED".into()),
947            EmptyQuery => None,
948            Fetch { .. } => None,
949            GrantedPrivilege => Some("GRANT".into()),
950            GrantedRole => Some("GRANT ROLE".into()),
951            Inserted(n) => {
952                // "On successful completion, an INSERT command returns a
953                // command tag of the form `INSERT <oid> <count>`."
954                //     -- https://www.postgresql.org/docs/11/sql-insert.html
955                //
956                // OIDs are a PostgreSQL-specific historical quirk, but we
957                // can return a 0 OID to indicate that the table does not
958                // have OIDs.
959                Some(format!("INSERT 0 {}", n))
960            }
961            Prepare => Some("PREPARE".into()),
962            Raised => Some("RAISE".into()),
963            ReassignOwned => Some("REASSIGN OWNED".into()),
964            RevokedPrivilege => Some("REVOKE".into()),
965            RevokedRole => Some("REVOKE ROLE".into()),
966            SendingRowsStreaming { .. } | SendingRowsImmediate { .. } => None,
967            SetVariable { reset: true, .. } => Some("RESET".into()),
968            SetVariable { reset: false, .. } => Some("SET".into()),
969            StartedTransaction { .. } => Some("BEGIN".into()),
970            Subscribing { .. } => None,
971            TransactionCommitted { .. } => Some("COMMIT".into()),
972            TransactionRolledBack { .. } => Some("ROLLBACK".into()),
973            Updated(n) => Some(format!("UPDATE {}", n)),
974            ValidatedConnection => Some("VALIDATE CONNECTION".into()),
975            CreatedIntrospectionSubscribe => Some("CREATE INTROSPECTION SUBSCRIBE".into()),
976        }
977    }
978
979    /// Expresses which [`PlanKind`] generate which set of [`ExecuteResponseKind`].
980    /// `ExecuteResponseKind::Canceled` could be generated at any point as well, but that is
981    /// excluded from this function.
982    pub fn generated_from(plan: &PlanKind) -> &'static [ExecuteResponseKind] {
983        use ExecuteResponseKind::*;
984        use PlanKind::*;
985
986        match plan {
987            AbortTransaction => &[TransactionRolledBack],
988            AlterClusterRename
989            | AlterClusterSwap
990            | AlterCluster
991            | AlterClusterReplicaRename
992            | AlterOwner
993            | AlterItemRename
994            | AlterRetainHistory
995            | AlterSourceTimestampInterval
996            | AlterNoop
997            | AlterSchemaRename
998            | AlterSchemaSwap
999            | AlterSecret
1000            | AlterConnection
1001            | AlterSource
1002            | AlterSink
1003            | AlterTableAddColumn
1004            | AlterMaterializedViewApplyReplacement
1005            | AlterQueryPolicy
1006            | AlterNetworkPolicy => &[AlteredObject],
1007            AlterDefaultPrivileges => &[AlteredDefaultPrivileges],
1008            AlterSetCluster => &[AlteredObject],
1009            AlterRole => &[AlteredRole],
1010            AlterSystemSet | AlterSystemReset | AlterSystemResetAll => {
1011                &[AlteredSystemConfiguration]
1012            }
1013            Close => &[ClosedCursor],
1014            PlanKind::CopyFrom => &[ExecuteResponseKind::CopyFrom, ExecuteResponseKind::Copied],
1015            PlanKind::CopyTo => &[ExecuteResponseKind::Copied],
1016            PlanKind::Comment => &[ExecuteResponseKind::Comment],
1017            CommitTransaction => &[TransactionCommitted, TransactionRolledBack],
1018            CreateConnection => &[CreatedConnection],
1019            CreateDatabase => &[CreatedDatabase],
1020            CreateSchema => &[CreatedSchema],
1021            CreateRole => &[CreatedRole],
1022            CreateCluster => &[CreatedCluster],
1023            CreateClusterReplica => &[CreatedClusterReplica],
1024            CreateSource | CreateSources => &[CreatedSource],
1025            CreateSecret => &[CreatedSecret],
1026            CreateSink => &[CreatedSink],
1027            CreateTable => &[CreatedTable],
1028            CreateView => &[CreatedView],
1029            CreateMaterializedView => &[CreatedMaterializedView],
1030            CreateIndex => &[CreatedIndex],
1031            CreateMetricSink => &[CreatedMetricSink],
1032            CreateType => &[CreatedType],
1033            PlanKind::Deallocate => &[ExecuteResponseKind::Deallocate],
1034            CreateNetworkPolicy => &[CreatedNetworkPolicy],
1035            CreateQueryPolicy => &[CreatedQueryPolicy],
1036            Declare => &[DeclaredCursor],
1037            DiscardTemp => &[DiscardedTemp],
1038            DiscardAll => &[DiscardedAll],
1039            DropObjects => &[DroppedObject],
1040            DropOwned => &[DroppedOwned],
1041            PlanKind::EmptyQuery => &[ExecuteResponseKind::EmptyQuery],
1042            ExplainPlan | ExplainPushdown | ExplainTimestamp | Select | ShowAllVariables
1043            | ShowCreate | ShowColumns | ShowVariable | InspectShard | ExplainSinkSchema => &[
1044                ExecuteResponseKind::CopyTo,
1045                SendingRowsStreaming,
1046                SendingRowsImmediate,
1047            ],
1048            Execute | ReadThenWrite => &[
1049                Deleted,
1050                Inserted,
1051                SendingRowsStreaming,
1052                SendingRowsImmediate,
1053                Updated,
1054            ],
1055            PlanKind::Fetch => &[ExecuteResponseKind::Fetch],
1056            GrantPrivileges => &[GrantedPrivilege],
1057            GrantRole => &[GrantedRole],
1058            Insert => &[Inserted, SendingRowsImmediate],
1059            PlanKind::Prepare => &[ExecuteResponseKind::Prepare],
1060            PlanKind::Raise => &[ExecuteResponseKind::Raised],
1061            PlanKind::ReassignOwned => &[ExecuteResponseKind::ReassignOwned],
1062            RevokePrivileges => &[RevokedPrivilege],
1063            RevokeRole => &[RevokedRole],
1064            PlanKind::SetVariable | ResetVariable | PlanKind::SetTransaction => {
1065                &[ExecuteResponseKind::SetVariable]
1066            }
1067            PlanKind::Subscribe => &[Subscribing, ExecuteResponseKind::CopyTo],
1068            StartTransaction => &[StartedTransaction],
1069            SideEffectingFunc => &[SendingRowsStreaming, SendingRowsImmediate],
1070            ValidateConnection => &[ExecuteResponseKind::ValidatedConnection],
1071        }
1072    }
1073}
1074
1075/// This implementation is meant to ensure that we maintain updated information
1076/// about which types of `ExecuteResponse`s are permitted to be sent, which will
1077/// be a function of which plan we're executing.
1078impl Transmittable for ExecuteResponse {
1079    type Allowed = ExecuteResponseKind;
1080    fn to_allowed(&self) -> Self::Allowed {
1081        ExecuteResponseKind::from(self)
1082    }
1083}