1use 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#[derive(Debug)]
71pub struct CopyFromStdinWriter {
72 pub batch_txs: Vec<mpsc::Sender<Vec<u8>>>,
75 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 outer_ctx_extra: Option<ExecuteContextExtra>,
138 },
139
140 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 UpdateScopedSystemParameters {
183 overrides: ScopedParameters,
184 prune_scope: ScopedParametersScope,
187 tx: oneshot::Sender<()>,
188 },
189
190 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 StartCopyFromStdin {
215 target_id: CatalogItemId,
216 target_name: String,
217 columns: Vec<ColumnIndex>,
218 row_desc: mz_repr::RelationDesc,
220 params: mz_pgcopy::CopyFormatParams<'static>,
222 session: Session,
223 tx: oneshot::Sender<Response<CopyFromStdinWriter>>,
224 },
225
226 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 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 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 CopyToPreflight {
314 s3_sink_connection: mz_compute_types::sinks::CopyToS3OneshotSinkConnection,
316 sink_id: GlobalId,
318 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 watch_set: Option<WatchSetCreation>,
331 tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
332 },
333
334 ExecuteSideEffectingFunc {
336 plan: SideEffectingFunc,
337 conn_id: ConnectionId,
338 tx: oneshot::Sender<Result<ExecuteResponse, AdapterError>>,
339 },
340
341 LookupConnection {
351 connection_id: u32,
352 tx: oneshot::Sender<Option<(ConnectionId, RoleId)>>,
353 },
354
355 InstallPeekWatchSets {
357 conn_id: ConnectionId,
358 watch_set: WatchSetCreation,
359 tx: oneshot::Sender<Result<(), AdapterError>>,
360 },
361
362 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 RegisterConnectionCancelWatch {
380 conn_id: ConnectionId,
381 tx: oneshot::Sender<watch::Receiver<bool>>,
382 },
383
384 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 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 DropInternalSubscribe {
423 sink_id: GlobalId,
424 },
425}
426
427#[derive(Debug)]
432pub enum WriteAttemptKind {
433 Session {
437 conn_id: ConnectionId,
438 write_ts: Option<mz_repr::Timestamp>,
439 },
440 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#[derive(Derivative)]
545#[derivative(Debug)]
546pub struct StartupResponse {
547 pub(crate) connection_peeks: Arc<crate::peek_registry::ConnectionPeeks>,
548 pub frontend_cancel_rx: tokio::sync::watch::Receiver<()>,
550 pub role_id: RoleId,
552 pub superuser_attribute: SuperuserAttribute,
557 #[derivative(Debug = "ignore")]
559 pub write_notify: BuiltinTableAppendNotify,
560 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 pub occ_write_semaphore: Arc<Semaphore>,
572 pub group_commit_notifier: crate::coord::appends::GroupCommitNotifier,
575 pub read_only: bool,
578}
579
580#[derive(Derivative)]
581#[derivative(Debug)]
582pub struct SASLChallengeResponse {
583 pub iteration_count: usize,
584 pub salt: String,
586 pub nonce: String,
587}
588
589#[derive(Derivative)]
590#[derivative(Debug)]
591pub struct SASLVerifyProofResponse {
592 pub verifier: String,
593}
594
595impl Transmittable for StartupResponse {
598 type Allowed = bool;
599 fn to_allowed(&self) -> Self::Allowed {
600 true
601 }
602}
603
604#[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#[derive(EnumKind, Derivative)]
634#[derivative(Debug)]
635#[enum_kind(ExecuteResponseKind, derive(PartialOrd, Ord))]
636pub enum ExecuteResponse {
637 AlteredDefaultPrivileges,
639 AlteredObject(ObjectType),
641 AlteredRole,
643 AlteredSystemConfiguration,
645 ClosedCursor,
647 Comment,
649 Copied(usize),
651 CopyTo {
653 format: mz_sql::plan::CopyFormat,
654 resp: Box<ExecuteResponse>,
655 },
656 CopyFrom {
657 target_id: CatalogItemId,
659 target_name: String,
661 columns: Vec<ColumnIndex>,
662 params: CopyFormatParams<'static>,
663 ctx_extra: ExecuteContextGuard,
664 },
665 CreatedConnection,
667 CreatedDatabase,
669 CreatedSchema,
671 CreatedRole,
673 CreatedCluster,
675 CreatedClusterReplica,
677 CreatedIndex,
679 CreatedMetricSink,
681 CreatedIntrospectionSubscribe,
683 CreatedSecret,
685 CreatedSink,
687 CreatedSource,
689 CreatedTable,
691 CreatedView,
693 CreatedViews,
695 CreatedMaterializedView,
697 CreatedType,
699 CreatedNetworkPolicy,
701 CreatedQueryPolicy,
703 Deallocate { all: bool },
705 DeclaredCursor,
707 Deleted(usize),
709 DiscardedTemp,
711 DiscardedAll {
713 params: BTreeMap<&'static str, String>,
715 },
716 DroppedObject(ObjectType),
718 DroppedOwned,
720 EmptyQuery,
722 Fetch {
724 name: String,
726 count: Option<FetchDirection>,
728 timeout: ExecuteTimeout,
730 ctx_extra: ExecuteContextGuard,
731 },
732 GrantedPrivilege,
734 GrantedRole,
736 Inserted(usize),
738 Prepare,
740 Raised,
742 ReassignOwned,
744 RevokedPrivilege,
746 RevokedRole,
748 SendingRowsStreaming {
750 #[derivative(Debug = "ignore")]
751 rows: Pin<Box<dyn Stream<Item = PeekResponseUnary> + Send + Sync>>,
752 instance_id: ComputeInstanceId,
753 strategy: StatementExecutionStrategy,
754 },
755 SendingRowsImmediate {
758 #[derivative(Debug = "ignore")]
759 rows: Box<dyn RowIterator + Send + Sync>,
760 },
761 SetVariable {
763 name: String,
764 reset: bool,
766 },
767 StartedTransaction,
769 Subscribing {
772 #[derivative(Debug = "ignore")]
773 rx: RowBatchStream,
774 ctx_extra: ExecuteContextGuard,
775 instance_id: ComputeInstanceId,
776 },
777 TransactionCommitted {
779 params: BTreeMap<&'static str, String>,
781 },
782 TransactionRolledBack {
784 params: BTreeMap<&'static str, String>,
786 },
787 Updated(usize),
789 ValidatedConnection,
791}
792
793impl TryFrom<&Statement<Raw>> for ExecuteResponse {
794 type Error = ();
795
796 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 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 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 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 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 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
1075impl Transmittable for ExecuteResponse {
1079 type Allowed = ExecuteResponseKind;
1080 fn to_allowed(&self) -> Self::Allowed {
1081 ExecuteResponseKind::from(self)
1082 }
1083}