1use std::collections::BTreeMap;
11use std::fmt::{Debug, Display, Formatter};
12use std::future::Future;
13use std::pin::{self, Pin};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use anyhow::bail;
18use chrono::{DateTime, Utc};
19use derivative::Derivative;
20use futures::{FutureExt, Stream, StreamExt};
21use itertools::Itertools;
22use mz_adapter_types::connection::{ConnectionId, ConnectionIdType};
23use mz_auth::password::Password;
24use mz_auth::{Authenticated, AuthenticatorKind};
25use mz_build_info::BuildInfo;
26use mz_compute_types::ComputeInstanceId;
27use mz_expr::UnmaterializableFunc;
28use mz_expr::{CollectionPlan, RowSetFinishing};
29use mz_ore::channel::OneshotReceiverExt;
30use mz_ore::collections::CollectionExt;
31use mz_ore::id_gen::{IdAllocator, IdAllocatorInnerBitSet, MAX_ORG_ID, org_id_conn_bits};
32use mz_ore::instrument;
33use mz_ore::now::{EpochMillis, NowFn, to_datetime};
34use mz_ore::str::StrExt;
35use mz_ore::task::AbortOnDropHandle;
36use mz_ore::thread::JoinOnDropHandle;
37use mz_ore::tracing::OpenTelemetryContext;
38use mz_repr::user::InternalUserMetadata;
39use mz_repr::{CatalogItemId, ColumnIndex, SqlScalarType};
40use mz_sql::ast::ConstantVisitor;
41use mz_sql::ast::{Raw, Statement};
42use mz_sql::catalog::{EnvironmentId, SessionCatalog};
43use mz_sql::plan::{MutationKind, Plan, ReadThenWritePlan};
44use mz_sql::session::hint::ApplicationNameHint;
45use mz_sql::session::metadata::SessionMetadata;
46use mz_sql::session::user::SUPPORT_USER;
47use mz_sql::session::vars::{CLUSTER, OwnedVarInput, SystemVars, Var};
48use mz_sql_parser::ast::display::AstDisplay;
49use mz_sql_parser::ast::{InsertStatement, StatementKind};
50use mz_sql_parser::parser::{ParserStatementError, StatementParseResult};
51use prometheus::Histogram;
52use serde_json::json;
53use tokio::sync::{mpsc, oneshot};
54use tracing::{debug, error};
55use uuid::Uuid;
56
57use crate::catalog::Catalog;
58use crate::command::{
59 CatalogDump, CatalogSnapshot, Command, CopyFromStdinWriter, ExecuteResponse, Response,
60 SASLChallengeResponse, SASLVerifyProofResponse, SuperuserAttribute,
61};
62use crate::config::{ScopedParameters, ScopedParametersScope, SystemParameterFrontend};
63use crate::coord::read_then_write::DependencyPolicy;
64use crate::coord::{Coordinator, ExecuteContextGuard};
65use crate::error::AdapterError;
66use crate::frontend_read_then_write::{
67 WriteAttemptState, WriteCancellation, contains_mz_now, validate_selection_dependencies,
68};
69use crate::metrics::Metrics;
70use crate::notice::ExecutionTimeKind;
71use crate::optimize::dataflows::{EvalTime, ExprPrepOneShot};
72use crate::optimize::{self, Optimize, OptimizerError};
73use crate::peek_client::{CoordinatorClient, ExecutionLogging, PeekCancelSafety, TakeOver};
74use crate::session::{
75 EndTransactionAction, PreparedStatement, Session, SessionConfig, StateRevision, TransactionId,
76 TransactionStatus,
77};
78use crate::statement_logging::{StatementEndedExecutionReason, StatementExecutionStrategy};
79use crate::telemetry::{self, EventDetails, SegmentClientExt, StatementFailureType};
80use crate::webhook::AppendWebhookResponse;
81use crate::{
82 AdapterNotice, AppendWebhookError, ExecutionTime, PeekClient, PeekResponseUnary,
83 StartupResponse,
84};
85
86pub struct Handle {
92 pub(crate) session_id: Uuid,
93 pub(crate) start_instant: Instant,
94 pub(crate) _thread: JoinOnDropHandle<()>,
95}
96
97impl Handle {
98 pub fn session_id(&self) -> Uuid {
104 self.session_id
105 }
106
107 pub fn start_instant(&self) -> Instant {
109 self.start_instant
110 }
111}
112
113#[derive(Debug, Clone)]
121pub struct Client {
122 build_info: &'static BuildInfo,
123 inner_cmd_tx: mpsc::UnboundedSender<(OpenTelemetryContext, Command)>,
124 id_alloc: IdAllocator<IdAllocatorInnerBitSet>,
125 now: NowFn,
126 metrics: Metrics,
127 environment_id: EnvironmentId,
128 segment_client: Option<mz_segment::Client>,
129}
130
131impl Client {
132 pub(crate) fn new(
133 build_info: &'static BuildInfo,
134 cmd_tx: mpsc::UnboundedSender<(OpenTelemetryContext, Command)>,
135 metrics: Metrics,
136 now: NowFn,
137 environment_id: EnvironmentId,
138 segment_client: Option<mz_segment::Client>,
139 ) -> Client {
140 let env_lower = org_id_conn_bits(&environment_id.organization_id());
148 Client {
149 build_info,
150 inner_cmd_tx: cmd_tx,
151 id_alloc: IdAllocator::new(1, MAX_ORG_ID, env_lower),
152 now,
153 metrics,
154 environment_id,
155 segment_client,
156 }
157 }
158
159 pub fn new_conn_id(&self) -> Result<ConnectionId, AdapterError> {
161 self.id_alloc.alloc().ok_or(AdapterError::IdExhaustionError)
162 }
163
164 pub fn new_session(&self, config: SessionConfig, _authenticated: Authenticated) -> Session {
170 Session::new(self.build_info, config, self.metrics().session_metrics())
174 }
175
176 pub async fn authenticate(
180 &self,
181 user: &String,
182 password: &Password,
183 ) -> Result<Authenticated, AdapterError> {
184 let (tx, rx) = oneshot::channel();
185 self.send(Command::AuthenticatePassword {
186 role_name: user.to_string(),
187 password: Some(password.clone()),
188 tx,
189 });
190 rx.await.expect("sender dropped")?;
191 Ok(Authenticated)
192 }
193
194 pub async fn generate_sasl_challenge(
197 &self,
198 user: &String,
199 client_nonce: &String,
200 ) -> Result<SASLChallengeResponse, AdapterError> {
201 let (tx, rx) = oneshot::channel();
202 self.send(Command::AuthenticateGetSASLChallenge {
203 role_name: user.to_string(),
204 nonce: client_nonce.to_string(),
205 tx,
206 });
207 let response = rx.await.expect("sender dropped")?;
208 Ok(response)
209 }
210
211 pub async fn verify_sasl_proof(
214 &self,
215 user: &String,
216 proof: &String,
217 nonce: &String,
218 mock_hash: &String,
219 ) -> Result<(SASLVerifyProofResponse, Authenticated), AdapterError> {
220 let (tx, rx) = oneshot::channel();
221 self.send(Command::AuthenticateVerifySASLProof {
222 role_name: user.to_string(),
223 proof: proof.to_string(),
224 auth_message: nonce.to_string(),
225 mock_hash: mock_hash.to_string(),
226 tx,
227 });
228 let response = rx.await.expect("sender dropped")?;
229 Ok((response, Authenticated))
230 }
231
232 pub async fn role_can_login(&self, role_name: &str) -> Result<(), AdapterError> {
234 let (tx, rx) = oneshot::channel();
235 self.send(Command::CheckRoleCanLogin {
236 role_name: role_name.to_string(),
237 tx,
238 });
239 rx.await.expect("sender dropped")
240 }
241
242 #[mz_ore::instrument(level = "debug")]
251 pub async fn startup(&self, session: Session) -> Result<SessionClient, AdapterError> {
252 let user = session.user().clone();
253 let conn_id = session.conn_id().clone();
254 let secret_key = session.secret_key();
255 let uuid = session.uuid();
256 let client_ip = session.client_ip();
257 let application_name = session.application_name().into();
258 let notice_tx = session.retain_notice_transmitter();
259
260 let (tx, rx) = oneshot::channel();
261
262 let rx = rx.with_guard(|resp: Result<StartupResponse, _>| {
273 if resp.is_ok() {
274 self.send(Command::Terminate {
275 conn_id: conn_id.clone(),
276 tx: None,
277 });
278 }
279 });
280
281 self.send(Command::Startup {
282 tx,
283 user,
284 conn_id: conn_id.clone(),
285 secret_key,
286 uuid,
287 client_ip: client_ip.copied(),
288 application_name,
289 notice_tx,
290 });
291
292 let response = rx.await.expect("sender dropped")?;
295
296 let StartupResponse {
300 connection_peeks,
301 role_id,
302 write_notify,
303 session_defaults,
304 catalog,
305 storage_collections,
306 transient_id_gen,
307 optimizer_metrics,
308 persist_client,
309 statement_logging_frontend,
310 superuser_attribute,
311 occ_write_semaphore,
312 group_commit_notifier,
313 read_only,
314 frontend_cancel_rx,
315 } = response;
316
317 let peek_client = PeekClient::new(
318 CoordinatorClient::Session(self.clone()),
319 connection_peeks,
320 &catalog,
321 storage_collections,
322 transient_id_gen,
323 optimizer_metrics,
324 persist_client,
325 statement_logging_frontend,
326 occ_write_semaphore,
327 group_commit_notifier,
328 read_only,
329 );
330
331 let mut client = SessionClient {
332 inner: Some(self.clone()),
333 session: Some(session),
334 timeouts: Timeout::new(),
335 environment_id: self.environment_id.clone(),
336 segment_client: self.segment_client.clone(),
337 peek_client,
338 enable_frontend_transaction_completion: false,
339 frontend_cancel_rx,
340 };
341
342 let session = client.session();
343
344 if let SuperuserAttribute(Some(superuser)) = superuser_attribute {
347 session.apply_internal_user_metadata(InternalUserMetadata { superuser });
348 }
349
350 session.initialize_role_metadata(role_id);
351 let vars_mut = session.vars_mut();
352 for (name, val) in session_defaults {
353 if let Err(err) = vars_mut.set_default(&name, val.borrow()) {
354 tracing::error!("failed to set peristed default, {err:?}");
357 }
358 }
359 session
360 .vars_mut()
361 .end_transaction(EndTransactionAction::Commit);
362
363 session.set_builtin_table_updates(write_notify);
371
372 let catalog = catalog.for_session(session);
373
374 let cluster_active = session.vars().cluster().to_string();
375 if session.vars().welcome_message() {
376 let cluster_info = if catalog.resolve_cluster(Some(&cluster_active)).is_err() {
377 format!("{cluster_active} (does not exist)")
378 } else {
379 cluster_active.to_string()
380 };
381
382 session.add_notice(AdapterNotice::Welcome(format!(
386 "connected to Materialize v{}
387 Environment ID: {}
388 Region: {}
389 User: {}
390 Cluster: {}
391 Database: {}
392 {}
393 Session UUID: {}
394
395Issue a SQL query to get started. Need help?
396 View documentation: https://materialize.com/s/docs
397 Join our Slack community: https://materialize.com/s/chat
398 ",
399 session.vars().build_info().semver_version(),
400 self.environment_id,
401 self.environment_id.region(),
402 session.vars().user().name,
403 cluster_info,
404 session.vars().database(),
405 match session.vars().search_path() {
406 [schema] => format!("Schema: {}", schema),
407 schemas => format!(
408 "Search path: {}",
409 schemas.iter().map(|id| id.to_string()).join(", ")
410 ),
411 },
412 session.uuid(),
413 )));
414 }
415
416 if session.vars().current_object_missing_warnings() {
417 if catalog.active_database().is_none() {
418 let db = session.vars().database().into();
419 session.add_notice(AdapterNotice::UnknownSessionDatabase(db));
420 }
421 }
422
423 let cluster_var = session
426 .vars()
427 .inspect(CLUSTER.name())
428 .expect("cluster should exist");
429 if session.vars().current_object_missing_warnings()
430 && catalog.resolve_cluster(Some(&cluster_active)).is_err()
431 {
432 let cluster_notice = 'notice: {
433 if cluster_var.inspect_session_value().is_some() {
434 break 'notice Some(AdapterNotice::DefaultClusterDoesNotExist {
435 name: cluster_active,
436 kind: "session",
437 suggested_action: "Pick an extant cluster with SET CLUSTER = name. Run SHOW CLUSTERS to see available clusters.".into(),
438 });
439 }
440
441 let role_default = catalog.get_role(catalog.active_role_id());
442 let role_cluster = match role_default.vars().get(CLUSTER.name()) {
443 Some(OwnedVarInput::Flat(name)) => Some(name),
444 None => None,
445 Some(v @ OwnedVarInput::SqlSet(_)) => {
447 tracing::warn!(?v, "SqlSet found for cluster Role Default");
448 break 'notice None;
449 }
450 };
451
452 let alter_role = "with `ALTER ROLE <role> SET cluster TO <cluster>;`";
453 match role_cluster {
454 None => Some(AdapterNotice::DefaultClusterDoesNotExist {
456 name: cluster_active,
457 kind: "system",
458 suggested_action: format!(
459 "Set a default cluster for the current role {alter_role}."
460 ),
461 }),
462 Some(_) => Some(AdapterNotice::DefaultClusterDoesNotExist {
464 name: cluster_active,
465 kind: "role",
466 suggested_action: format!(
467 "Change the default cluster for the current role {alter_role}."
468 ),
469 }),
470 }
471 };
472
473 if let Some(notice) = cluster_notice {
474 session.add_notice(notice);
475 }
476 }
477
478 let enable_frontend_transaction_completion =
479 mz_sql::session::vars::ENABLE_FRONTEND_TRANSACTION_COMPLETION
480 .require(catalog.system_vars())
481 .is_ok();
482 client.enable_frontend_transaction_completion = enable_frontend_transaction_completion;
483 Ok(client)
484 }
485
486 pub fn cancel_request(&self, conn_id: ConnectionIdType, secret_key: u32) {
488 self.send(Command::CancelRequest {
489 conn_id,
490 secret_key,
491 });
492 }
493
494 pub async fn support_execute_one(
497 &self,
498 sql: &str,
499 ) -> Result<Pin<Box<dyn Stream<Item = PeekResponseUnary> + Send>>, anyhow::Error> {
500 let conn_id = self.new_conn_id()?;
502 let session = self.new_session(
503 SessionConfig {
504 conn_id,
505 uuid: Uuid::new_v4(),
506 user: SUPPORT_USER.name.clone(),
507 client_ip: None,
508 external_metadata_rx: None,
509 helm_chart_version: None,
510 authenticator_kind: AuthenticatorKind::None,
511 groups: None,
512 },
513 Authenticated,
514 );
515 let mut session_client = self.startup(session).await?;
516
517 let stmts = mz_sql::parse::parse(sql)?;
519 if stmts.len() != 1 {
520 bail!("must supply exactly one query");
521 }
522 let StatementParseResult { ast: stmt, sql } = stmts.into_element();
523
524 const EMPTY_PORTAL: &str = "";
525 session_client.start_transaction(Some(1))?;
526 session_client
527 .declare(EMPTY_PORTAL.into(), stmt, sql.to_string())
528 .await?;
529
530 let execute_result = session_client
531 .execute(EMPTY_PORTAL.into(), futures::future::pending(), None)
532 .await?;
533 match execute_result {
534 (ExecuteResponse::SendingRowsStreaming { mut rows, .. }, _) => {
535 let owning_response_stream = async_stream::stream! {
540 while let Some(rows) = rows.next().await {
541 yield rows;
542 }
543 drop(session_client);
544 };
545 Ok(Box::pin(owning_response_stream))
546 }
547 r => bail!("unsupported response type: {r:?}"),
548 }
549 }
550
551 pub fn metrics(&self) -> &Metrics {
553 &self.metrics
554 }
555
556 pub fn now(&self) -> DateTime<Utc> {
558 to_datetime((self.now)())
559 }
560
561 pub async fn get_webhook_appender(
563 &self,
564 database: String,
565 schema: String,
566 name: String,
567 ) -> Result<AppendWebhookResponse, AppendWebhookError> {
568 let (tx, rx) = oneshot::channel();
569
570 self.send(Command::GetWebhook {
572 database,
573 schema,
574 name,
575 tx,
576 });
577
578 let response = rx
580 .await
581 .map_err(|_| anyhow::anyhow!("failed to receive webhook response"))?;
582
583 response
584 }
585
586 pub async fn get_system_vars(&self) -> SystemVars {
588 let (tx, rx) = oneshot::channel();
589 self.send(Command::GetSystemVars { tx });
590 rx.await.expect("coordinator unexpectedly gone")
591 }
592
593 pub async fn catalog_snapshot_expensive(&self) -> Arc<Catalog> {
599 let (tx, rx) = oneshot::channel();
600 self.send(Command::CatalogSnapshot { tx });
601 let CatalogSnapshot { catalog } = rx.await.expect("coordinator unexpectedly gone");
602 catalog
603 }
604
605 pub async fn update_scoped_system_parameters(
614 &self,
615 overrides: ScopedParameters,
616 prune_scope: ScopedParametersScope,
617 ) {
618 let (tx, rx) = oneshot::channel();
619 self.send(Command::UpdateScopedSystemParameters {
620 overrides,
621 prune_scope,
622 tx,
623 });
624 let _ = rx.await;
625 }
626
627 pub fn install_scoped_system_parameter_frontend(&self, frontend: Arc<SystemParameterFrontend>) {
632 self.send(Command::InstallScopedSystemParameterFrontend { frontend });
633 }
634
635 #[instrument(level = "debug")]
636 pub(crate) fn try_send(&self, cmd: Command) -> bool {
637 self.inner_cmd_tx
638 .send((OpenTelemetryContext::obtain(), cmd))
639 .is_ok()
640 }
641
642 #[instrument(level = "debug")]
643 pub(crate) fn send(&self, cmd: Command) {
644 assert!(self.try_send(cmd), "coordinator unexpectedly gone");
645 }
646}
647
648pub struct SessionClient {
652 inner: Option<Client>,
656 session: Option<Session>,
659 timeouts: Timeout,
660 segment_client: Option<mz_segment::Client>,
661 environment_id: EnvironmentId,
662 peek_client: PeekClient,
664 enable_frontend_transaction_completion: bool,
665 frontend_cancel_rx: tokio::sync::watch::Receiver<()>,
666}
667
668impl SessionClient {
669 pub fn parse<'a>(
672 &self,
673 sql: &'a str,
674 ) -> Result<Result<Vec<StatementParseResult<'a>>, ParserStatementError>, String> {
675 match mz_sql::parse::parse_with_limit(sql) {
676 Ok(Err(e)) => {
677 self.track_statement_parse_failure(&e);
678 Ok(Err(e))
679 }
680 r => r,
681 }
682 }
683
684 fn track_statement_parse_failure(&self, parse_error: &ParserStatementError) {
685 let session = self.session.as_ref().expect("session invariant violated");
686 let Some(user_id) = session.user().external_metadata.as_ref().map(|m| m.user_id) else {
687 return;
688 };
689 let Some(segment_client) = &self.segment_client else {
690 return;
691 };
692 let Some(statement_kind) = parse_error.statement else {
693 return;
694 };
695 let Some((action, object_type)) = telemetry::analyze_audited_statement(statement_kind)
696 else {
697 return;
698 };
699 let event_type = StatementFailureType::ParseFailure;
700 let event_name = format!(
701 "{} {} {}",
702 object_type.as_title_case(),
703 action.as_title_case(),
704 event_type.as_title_case(),
705 );
706 segment_client.environment_track(
707 &self.environment_id,
708 event_name,
709 json!({
710 "statement_kind": statement_kind,
711 "error": &parse_error.error,
712 }),
713 EventDetails {
714 user_id: Some(user_id),
715 application_name: Some(session.application_name()),
716 ..Default::default()
717 },
718 );
719 }
720
721 pub async fn get_prepared_statement(
724 &mut self,
725 name: &str,
726 ) -> Result<&PreparedStatement, AdapterError> {
727 let catalog = self.catalog_snapshot("get_prepared_statement").await;
728 Coordinator::verify_prepared_statement(&catalog, self.session(), name)?;
729 Ok(self
730 .session()
731 .get_prepared_statement_unverified(name)
732 .expect("must exist"))
733 }
734
735 pub async fn prepare(
740 &mut self,
741 name: String,
742 stmt: Option<Statement<Raw>>,
743 sql: String,
744 param_types: Vec<Option<SqlScalarType>>,
745 ) -> Result<(), AdapterError> {
746 let catalog = self.catalog_snapshot("prepare").await;
747
748 let mut async_pause = false;
751 (|| {
752 fail::fail_point!("async_prepare", |val| {
753 async_pause = val.map_or(false, |val| val.parse().unwrap_or(false))
754 });
755 })();
756 if async_pause {
757 tokio::time::sleep(Duration::from_secs(1)).await;
758 };
759
760 let desc = Coordinator::describe(&catalog, self.session(), stmt.clone(), param_types)?;
761 let now = self.now();
762 let state_revision = StateRevision {
763 catalog_revision: catalog.transient_revision(),
764 session_state_revision: self.session().state_revision(),
765 };
766 self.session()
767 .set_prepared_statement(name, stmt, sql, desc, state_revision, now);
768 Ok(())
769 }
770
771 #[mz_ore::instrument(level = "debug")]
773 pub async fn declare(
774 &mut self,
775 name: String,
776 stmt: Statement<Raw>,
777 sql: String,
778 ) -> Result<(), AdapterError> {
779 let catalog = self.catalog_snapshot("declare").await;
780 let param_types = vec![];
781 let desc =
782 Coordinator::describe(&catalog, self.session(), Some(stmt.clone()), param_types)?;
783 let params = vec![];
784 let result_formats = vec![mz_pgwire_common::Format::Text; desc.arity()];
785 let now = self.now();
786 let logging = self.session().mint_logging(sql, Some(&stmt), now);
787 let state_revision = StateRevision {
788 catalog_revision: catalog.transient_revision(),
789 session_state_revision: self.session().state_revision(),
790 };
791 self.session().set_portal(
792 name,
793 desc,
794 Some(stmt),
795 logging,
796 params,
797 result_formats,
798 state_revision,
799 )?;
800 Ok(())
801 }
802
803 #[mz_ore::instrument(level = "debug")]
810 pub async fn execute(
811 &mut self,
812 portal_name: String,
813 cancel_future: impl Future<Output = std::io::Error> + Send,
814 outer_ctx_extra: Option<ExecuteContextGuard>,
815 ) -> Result<(ExecuteResponse, Instant), AdapterError> {
816 let execute_started = Instant::now();
817 self.frontend_cancel_rx.borrow_and_update();
818 let cancel_future = cancel_future.map(|_| ()).shared();
819
820 let mut logging = ExecutionLogging::adopt(outer_ctx_extra, &self.peek_client);
824
825 let result = self
826 .execute_attempts(portal_name, &mut logging, cancel_future)
827 .await;
828
829 self.session().advance_state_revision();
832
833 logging.retire(&result);
834
835 result.map(|response| (response, execute_started))
836 }
837
838 async fn execute_attempts(
842 &mut self,
843 portal_name: String,
844 logging: &mut ExecutionLogging,
845 cancel_future: impl Future<Output = ()> + Send + Clone,
846 ) -> Result<ExecuteResponse, AdapterError> {
847 let portal_name = self.unroll_sql_execute(portal_name, logging).await?;
860
861 let peek_result = self
864 .try_peek(&portal_name, logging, cancel_future.clone())
865 .await?;
866 if let Some(resp) = peek_result {
867 debug!("frontend peek succeeded");
868 return Ok(resp);
869 }
870 debug!("frontend peek did not happen, trying frontend read-then-write");
871
872 let rtw_result = self
874 .try_read_then_write_with_cancel(&portal_name, logging, cancel_future.clone())
875 .await?;
876 if let Some(resp) = rtw_result {
877 debug!("frontend read-then-write succeeded");
878 return Ok(resp);
879 }
880 debug!("frontend read-then-write did not happen, falling back to `Command::Execute`");
881
882 let outer_ctx_extra = logging.release();
885 self.send_with_cancel(
886 |tx, session| Command::Execute {
887 portal_name,
888 session,
889 tx,
890 outer_ctx_extra,
891 },
892 cancel_future,
893 )
894 .await
895 }
896
897 async fn unroll_sql_execute(
911 &mut self,
912 portal_name: String,
913 logging: &mut ExecutionLogging,
914 ) -> Result<String, AdapterError> {
915 let (stmt, params, outer_logging, outer_lifecycle_timestamps) = {
916 let session = self.session.as_ref().expect("SessionClient invariant");
917 let portal = match session.get_portal_unverified(&portal_name) {
918 Some(p) => p,
919 None => return Ok(portal_name),
923 };
924 match &portal.stmt {
925 Some(stmt) => (
926 Arc::clone(stmt),
927 portal.parameters.clone(),
928 Arc::clone(&portal.logging),
929 portal.lifecycle_timestamps.clone(),
930 ),
931 None => return Ok(portal_name),
932 }
933 };
934
935 if !matches!(&*stmt, Statement::Execute(_)) {
938 return Ok(portal_name);
939 }
940
941 let catalog = self.catalog_snapshot("unroll_sql_execute").await;
942
943 {
947 let session = self.session.as_mut().expect("SessionClient invariant");
948 Coordinator::verify_portal(&catalog, session, &portal_name)?;
949 }
950
951 logging.take_over(
959 &self.peek_client,
960 self.session.as_mut().expect("SessionClient invariant"),
961 Some(&stmt),
962 ¶ms,
963 &outer_logging,
964 &catalog,
965 outer_lifecycle_timestamps,
966 TakeOver::UnrolledExecute,
967 );
968
969 self.install_inner_portal_for_execute(&catalog, &stmt, ¶ms)
970 }
971
972 fn install_inner_portal_for_execute(
977 &mut self,
978 catalog: &Arc<Catalog>,
979 stmt: &Arc<Statement<Raw>>,
980 params: &mz_sql::plan::Params,
981 ) -> Result<String, AdapterError> {
982 use mz_sql::plan::Plan;
983
984 let execute_plan = {
985 let session = self.session.as_mut().expect("SessionClient invariant");
986 let conn_catalog = catalog.for_session(session);
987 let (resolved_stmt, resolved_ids) =
988 mz_sql::names::resolve(&conn_catalog, (**stmt).clone())?;
989 let pcx = session.pcx();
990 let (plan, _sql_impl_ids) = mz_sql::plan::plan(
991 Some(pcx),
992 &conn_catalog,
993 resolved_stmt,
994 params,
995 &resolved_ids,
996 )?;
997 match plan {
998 Plan::Execute(plan) => plan,
999 other => {
1000 return Err(AdapterError::Internal(format!(
1004 "planning Statement::Execute yielded unexpected plan: {:?}",
1005 mz_sql::plan::PlanKind::from(&other),
1006 )));
1007 }
1008 }
1009 };
1010
1011 let session = self.session.as_mut().expect("SessionClient invariant");
1017 Coordinator::verify_prepared_statement(catalog, session, &execute_plan.name)?;
1018 let ps = session
1019 .get_prepared_statement_unverified(&execute_plan.name)
1020 .expect("verified above");
1021 let inner_stmt = ps.stmt().cloned();
1022 let inner_desc = ps.desc().clone();
1023 let state_revision = ps.state_revision;
1024 let inner_logging = Arc::clone(ps.logging());
1025
1026 if let Some(inner) = inner_stmt.as_ref() {
1031 if matches!(inner, Statement::Execute(_)) {
1032 return Err(AdapterError::Internal(format!(
1033 "nested EXECUTE: prepared statement {} resolves to another EXECUTE; \
1034 parser should reject `PREPARE ... AS EXECUTE ...`",
1035 execute_plan.name.quoted(),
1036 )));
1037 }
1038 }
1039
1040 session.create_new_portal(
1041 inner_stmt,
1042 inner_logging,
1043 inner_desc,
1044 execute_plan.params,
1045 Vec::new(),
1046 state_revision,
1047 )
1048 }
1049
1050 fn now(&self) -> EpochMillis {
1051 (self.inner().now)()
1052 }
1053
1054 fn now_datetime(&self) -> DateTime<Utc> {
1055 to_datetime(self.now())
1056 }
1057
1058 pub fn start_transaction(&mut self, implicit: Option<usize>) -> Result<(), AdapterError> {
1064 let now = self.now_datetime();
1065 let session = self.session.as_mut().expect("session invariant violated");
1066 let result = match implicit {
1067 None => session.start_transaction(now, None, None),
1068 Some(stmts) => {
1069 session.start_transaction_implicit(now, stmts);
1070 Ok(())
1071 }
1072 };
1073 result
1074 }
1075
1076 #[instrument(level = "debug")]
1079 pub async fn end_transaction(
1080 &mut self,
1081 action: EndTransactionAction,
1082 ) -> Result<ExecuteResponse, AdapterError> {
1083 if self.enable_frontend_transaction_completion {
1084 if let Some(completion) = self.session().read_only_completion(action) {
1085 return crate::frontend_transaction::complete_read_only_transaction(
1086 self.session.as_mut().expect("session invariant violated"),
1087 &mut self.peek_client,
1088 &mut self.frontend_cancel_rx,
1089 completion,
1090 )
1091 .await;
1092 }
1093 }
1094 let res = self
1095 .send(|tx, session| Command::Commit {
1096 action,
1097 session,
1098 tx,
1099 })
1100 .await;
1101 let _ = self.session().clear_transaction();
1105 res
1106 }
1107
1108 pub async fn settle_statement(
1117 &mut self,
1118 commit_implicit_transaction: bool,
1119 ) -> Result<SettledStatement, AdapterError> {
1120 let mut reverted = BTreeMap::new();
1121 if commit_implicit_transaction && self.session().transaction().is_implicit() {
1122 let response = self.end_transaction(EndTransactionAction::Commit).await?;
1123 if let ExecuteResponse::TransactionCommitted { params } = response {
1124 reverted = params;
1125 }
1126 }
1127 Ok(SettledStatement { reverted })
1128 }
1129
1130 pub fn fail_transaction(&mut self) {
1132 let session = self.session.take().expect("session invariant violated");
1133 let session = session.fail_transaction();
1134 self.session = Some(session);
1135 }
1136
1137 #[instrument(level = "debug")]
1141 pub async fn catalog_snapshot(&mut self, context: &str) -> Arc<Catalog> {
1142 self.peek_client.catalog_snapshot(context).await
1143 }
1144
1145 pub async fn statement_arrival_logging_enabled(&mut self) -> bool {
1147 let catalog = self.catalog_snapshot("statement_arrival_logging").await;
1148 catalog.system_config().enable_statement_arrival_logging()
1149 }
1150
1151 pub async fn extended_protocol_implicit_transaction_enabled(&mut self) -> bool {
1153 let catalog = self
1154 .catalog_snapshot("extended_protocol_implicit_transaction")
1155 .await;
1156 catalog
1157 .system_config()
1158 .enable_extended_protocol_implicit_transaction()
1159 }
1160
1161 pub async fn dump_catalog(&mut self) -> Result<CatalogDump, AdapterError> {
1166 let catalog = self.catalog_snapshot("dump_catalog").await;
1167 catalog.dump().map_err(AdapterError::from)
1168 }
1169
1170 pub async fn check_catalog(&mut self) -> Result<(), serde_json::Value> {
1176 let catalog = self.catalog_snapshot("check_catalog").await;
1177 catalog.check_consistency()
1178 }
1179
1180 pub async fn check_coordinator(&self) -> Result<(), serde_json::Value> {
1186 self.send_without_session(|tx| Command::CheckConsistency { tx })
1187 .await
1188 .map_err(|inconsistencies| {
1189 serde_json::to_value(inconsistencies).unwrap_or_else(|_| {
1190 serde_json::Value::String("failed to serialize inconsistencies".to_string())
1191 })
1192 })
1193 }
1194
1195 pub async fn dump_coordinator_state(&self) -> Result<serde_json::Value, anyhow::Error> {
1196 self.send_without_session(|tx| Command::Dump { tx }).await
1197 }
1198
1199 pub fn retire_execute(
1202 &self,
1203 guard: ExecuteContextGuard,
1204 reason: StatementEndedExecutionReason,
1205 ) {
1206 if !guard.is_trivial() {
1207 let data = guard.defuse();
1208 let cmd = Command::RetireExecute { data, reason };
1209 self.inner().send(cmd);
1210 }
1211 }
1212
1213 pub async fn start_copy_from_stdin(
1219 &mut self,
1220 target_id: CatalogItemId,
1221 target_name: String,
1222 columns: Vec<ColumnIndex>,
1223 row_desc: mz_repr::RelationDesc,
1224 params: mz_pgcopy::CopyFormatParams<'static>,
1225 ) -> Result<CopyFromStdinWriter, AdapterError> {
1226 self.send(|tx, session| Command::StartCopyFromStdin {
1227 target_id,
1228 target_name,
1229 columns,
1230 row_desc,
1231 params,
1232 session,
1233 tx,
1234 })
1235 .await
1236 }
1237
1238 pub fn stage_copy_from_stdin_batches(
1243 &mut self,
1244 target_id: CatalogItemId,
1245 batches: Vec<mz_persist_client::batch::ProtoBatch>,
1246 ) -> Result<(), AdapterError> {
1247 use crate::session::{TransactionOps, WriteOp};
1248 use mz_storage_client::client::TableData;
1249
1250 self.session()
1251 .add_transaction_ops(TransactionOps::Writes(vec![WriteOp {
1252 id: target_id,
1253 rows: TableData::Batches(batches.into()),
1254 }]))?;
1255 Ok(())
1256 }
1257
1258 pub async fn get_system_vars(&self) -> SystemVars {
1260 self.inner().get_system_vars().await
1261 }
1262
1263 pub async fn set_system_vars(
1265 &mut self,
1266 vars: BTreeMap<String, String>,
1267 ) -> Result<(), AdapterError> {
1268 let conn_id = self.session().conn_id().clone();
1269 self.send_without_session(|tx| Command::SetSystemVars { vars, conn_id, tx })
1270 .await
1271 }
1272
1273 pub async fn inject_audit_events(
1278 &mut self,
1279 events: Vec<crate::catalog::InjectedAuditEvent>,
1280 ) -> Result<(), AdapterError> {
1281 let conn_id = self.session().conn_id().clone();
1282 self.send_without_session(|tx| Command::InjectAuditEvents {
1283 events,
1284 conn_id,
1285 tx,
1286 })
1287 .await
1288 }
1289
1290 pub async fn terminate(&mut self) {
1292 let conn_id = self.session().conn_id().clone();
1293 let res = self
1294 .send_without_session(|tx| Command::Terminate {
1295 conn_id,
1296 tx: Some(tx),
1297 })
1298 .await;
1299 if let Err(e) = res {
1300 error!("Unable to terminate session: {e:?}");
1302 }
1303 self.inner = None;
1305 }
1306
1307 pub fn session(&mut self) -> &mut Session {
1309 self.session.as_mut().expect("session invariant violated")
1310 }
1311
1312 pub fn inner(&self) -> &Client {
1314 self.inner.as_ref().expect("inner invariant violated")
1315 }
1316
1317 async fn send_without_session<T, F>(&self, f: F) -> T
1318 where
1319 F: FnOnce(oneshot::Sender<T>) -> Command,
1320 {
1321 let (tx, rx) = oneshot::channel();
1322 self.inner().send(f(tx));
1323 rx.await.expect("sender dropped")
1324 }
1325
1326 #[instrument(level = "debug")]
1327 async fn send<T, F>(&mut self, f: F) -> Result<T, AdapterError>
1328 where
1329 F: FnOnce(oneshot::Sender<Response<T>>, Session) -> Command,
1330 {
1331 self.send_with_cancel(f, futures::future::pending()).await
1332 }
1333
1334 #[instrument(level = "debug")]
1338 async fn send_with_cancel<T, F>(
1339 &mut self,
1340 f: F,
1341 cancel_future: impl Future<Output = ()> + Send,
1342 ) -> Result<T, AdapterError>
1343 where
1344 F: FnOnce(oneshot::Sender<Response<T>>, Session) -> Command,
1345 {
1346 let session = self.session.take().expect("session invariant violated");
1347 let mut typ = None;
1348 let application_name = session.application_name();
1349 let name_hint = ApplicationNameHint::from_str(application_name);
1350 let conn_id = session.conn_id().clone();
1351 let (tx, rx) = oneshot::channel();
1352
1353 let Self {
1356 inner: inner_client,
1357 session: client_session,
1358 ..
1359 } = self;
1360
1361 let inner_client = inner_client.as_ref().expect("inner invariant violated");
1364
1365 let mut guarded_rx = rx.with_guard(|response: Response<_>| {
1371 *client_session = Some(response.session);
1372 });
1373
1374 inner_client.send({
1375 let cmd = f(tx, session);
1376 match cmd {
1380 Command::Execute { .. } => typ = Some("execute"),
1381 Command::GetWebhook { .. } => typ = Some("webhook"),
1382 Command::StartCopyFromStdin { .. }
1383 | Command::Startup { .. }
1384 | Command::AuthenticatePassword { .. }
1385 | Command::AuthenticateGetSASLChallenge { .. }
1386 | Command::AuthenticateVerifySASLProof { .. }
1387 | Command::CheckRoleCanLogin { .. }
1388 | Command::CatalogSnapshot { .. }
1389 | Command::Commit { .. }
1390 | Command::CancelRequest { .. }
1391 | Command::PrivilegedCancelRequest { .. }
1392 | Command::GetSystemVars { .. }
1393 | Command::SetSystemVars { .. }
1394 | Command::UpdateScopedSystemParameters { .. }
1395 | Command::InstallScopedSystemParameterFrontend { .. }
1396 | Command::Terminate { .. }
1397 | Command::RetireExecute { .. }
1398 | Command::CheckConsistency { .. }
1399 | Command::Dump { .. }
1400 | Command::GetComputeInstanceClient { .. }
1401 | Command::GetOracle { .. }
1402 | Command::DetermineRealTimeRecentTimestamp { .. }
1403 | Command::GetTransactionReadHoldsBundle { .. }
1404 | Command::StoreTransactionReadHolds { .. }
1405 | Command::ExecuteSlowPathPeek { .. }
1406 | Command::ExecuteSubscribe { .. }
1407 | Command::CopyToPreflight { .. }
1408 | Command::ExecuteCopyTo { .. }
1409 | Command::ExecuteSideEffectingFunc { .. }
1410 | Command::LookupConnection { .. }
1411 | Command::InstallPeekWatchSets { .. }
1412 | Command::ExplainTimestamp { .. }
1413 | Command::InjectAuditEvents { .. }
1414 | Command::RegisterConnectionCancelWatch { .. }
1415 | Command::CreateInternalSubscribe { .. }
1416 | Command::AttemptWrite { .. }
1417 | Command::DropInternalSubscribe { .. } => {}
1418 };
1419 cmd
1420 });
1421
1422 let mut cancel_future = pin::pin!(cancel_future);
1423 let mut cancelled = false;
1424 loop {
1425 tokio::select! {
1426 res = &mut guarded_rx => {
1427 drop(guarded_rx);
1429
1430 let res = res.expect("sender dropped");
1431 let status = res.result.is_ok().then_some("success").unwrap_or("error");
1432 if let Err(err) = res.result.as_ref() {
1433 if name_hint.should_trace_errors() {
1434 tracing::warn!(?err, ?name_hint, "adapter response error");
1435 }
1436 }
1437
1438 if let Some(typ) = typ {
1439 inner_client
1440 .metrics
1441 .commands
1442 .with_label_values(&[typ, status, name_hint.as_str()])
1443 .inc();
1444 }
1445 *client_session = Some(res.session);
1446 return res.result;
1447 },
1448 _ = &mut cancel_future, if !cancelled => {
1449 cancelled = true;
1450 inner_client.send(Command::PrivilegedCancelRequest {
1451 conn_id: conn_id.clone(),
1452 });
1453 }
1454 };
1455 }
1456 }
1457
1458 pub fn add_idle_in_transaction_session_timeout(&mut self) {
1459 let session = self.session();
1460 let timeout_dur = session.vars().idle_in_transaction_session_timeout();
1461 if !timeout_dur.is_zero() {
1462 let timeout_dur = timeout_dur.clone();
1463 if let Some(txn) = session.transaction().inner() {
1464 let txn_id = txn.id.clone();
1465 let timeout = TimeoutType::IdleInTransactionSession(txn_id);
1466 self.timeouts.add_timeout(timeout, timeout_dur);
1467 }
1468 }
1469 }
1470
1471 pub fn remove_idle_in_transaction_session_timeout(&mut self) {
1472 let session = self.session();
1473 if let Some(txn) = session.transaction().inner() {
1474 let txn_id = txn.id.clone();
1475 self.timeouts
1476 .remove_timeout(&TimeoutType::IdleInTransactionSession(txn_id));
1477 }
1478 }
1479
1480 pub async fn recv_timeout(&mut self) -> Option<TimeoutType> {
1487 self.timeouts.recv().await
1488 }
1489
1490 pub(crate) async fn try_peek(
1496 &mut self,
1497 portal_name: &str,
1498 logging: &mut ExecutionLogging,
1499 connection_closed: impl Future<Output = ()> + Send,
1500 ) -> Result<Option<ExecuteResponse>, AdapterError> {
1501 let connection = Arc::clone(self.peek_client.connection_peeks());
1502 let mut cancellation = self.frontend_cancel_rx.clone();
1503 let cancel_safety = PeekCancelSafety::new();
1504 let session = self.session.as_mut().expect("SessionClient invariant");
1505 let attempt = self
1506 .peek_client
1507 .try_peek(portal_name, session, logging, &cancel_safety);
1508 tokio::pin!(attempt);
1509 let connection_cancel = async move {
1510 if cancellation.changed().await.is_err() {
1511 futures::future::pending::<()>().await;
1512 }
1513 };
1514 tokio::select! {
1515 biased;
1516 _ = connection_cancel => {}
1517 _ = connection_closed => {}
1518 result = &mut attempt => return result,
1519 }
1520 if cancel_safety.can_abort() {
1521 connection.cancel();
1525 Err(AdapterError::Canceled)
1526 } else {
1527 attempt.await
1530 }
1531 }
1532
1533 fn read_then_write_applies(&self, portal_name: &str) -> bool {
1541 let session = self.session.as_ref().expect("SessionClient invariant");
1542 match session.get_portal_unverified(portal_name) {
1543 Some(portal) => portal
1544 .stmt
1545 .as_deref()
1546 .is_some_and(is_read_then_write_statement),
1547 None => false,
1548 }
1549 }
1550
1551 async fn try_read_then_write_with_cancel(
1562 &mut self,
1563 portal_name: &str,
1564 logging: &mut ExecutionLogging,
1565 cancel_future: impl Future<Output = ()> + Send,
1566 ) -> Result<Option<ExecuteResponse>, AdapterError> {
1567 if !self.read_then_write_applies(portal_name) {
1572 return Ok(None);
1573 }
1574
1575 self.session().require_coordinator_completion();
1576 let conn_id = self.session().conn_id().clone();
1577 let statement_timeout = *self.session().vars().statement_timeout();
1578 let inner_client = self.inner().clone();
1579 let attempt_state = Arc::new(WriteAttemptState::new());
1580
1581 let mut cancel_future = pin::pin!(cancel_future);
1582 let statement_timeout = async move {
1583 if statement_timeout.is_zero() {
1584 futures::future::pending::<()>().await;
1585 } else {
1586 tokio::time::sleep(statement_timeout).await;
1587 }
1588 };
1589 tokio::pin!(statement_timeout);
1590
1591 let mut connection_cancel_rx = {
1597 let register =
1598 self.peek_client
1599 .call_coordinator(|tx| Command::RegisterConnectionCancelWatch {
1600 conn_id: conn_id.clone(),
1601 tx,
1602 });
1603 tokio::pin!(register);
1604 tokio::select! {
1605 rx = &mut register => rx?,
1606 _ = &mut cancel_future => {
1607 inner_client.try_send(Command::PrivilegedCancelRequest {
1608 conn_id: conn_id.clone(),
1609 });
1610 return Err(AdapterError::Canceled);
1611 }
1612 _ = &mut statement_timeout => {
1613 inner_client.try_send(Command::PrivilegedCancelRequest {
1614 conn_id: conn_id.clone(),
1615 });
1616 return Err(AdapterError::StatementTimeout);
1617 }
1618 }
1619 };
1620 if *connection_cancel_rx.borrow() {
1621 return Err(AdapterError::Canceled);
1622 }
1623 let connection_cancel = async move {
1624 if connection_cancel_rx.wait_for(|v| *v).await.is_err() {
1625 futures::future::pending::<()>().await;
1626 }
1627 };
1628 tokio::pin!(connection_cancel);
1629
1630 let read_then_write =
1631 self.try_read_then_write(portal_name, logging, Arc::clone(&attempt_state));
1632 tokio::pin!(read_then_write);
1633
1634 let requested = tokio::select! {
1635 response = &mut read_then_write => return response,
1636 _ = &mut cancel_future => WriteCancellation::Canceled,
1637 _ = &mut connection_cancel => WriteCancellation::Canceled,
1638 _ = &mut statement_timeout => WriteCancellation::StatementTimeout,
1639 };
1640
1641 attempt_state.request(requested);
1642 inner_client.try_send(Command::PrivilegedCancelRequest {
1643 conn_id: conn_id.clone(),
1644 });
1645
1646 if !attempt_state.write_submitted() {
1647 return Err(requested.into());
1648 }
1649
1650 read_then_write.await
1653 }
1654
1655 async fn try_read_then_write(
1662 &mut self,
1663 portal_name: &str,
1664 logging: &mut ExecutionLogging,
1665 attempt_state: Arc<WriteAttemptState>,
1666 ) -> Result<Option<ExecuteResponse>, AdapterError> {
1667 let catalog = self.catalog_snapshot("try_read_then_write").await;
1668
1669 let stmt = {
1670 let session = self.session.as_ref().expect("SessionClient invariant");
1671 let portal = match session.get_portal_unverified(portal_name) {
1672 Some(portal) => portal,
1673 None => return Ok(None), };
1675 portal.stmt.clone()
1676 };
1677
1678 let stmt = match stmt {
1679 Some(stmt) if is_read_then_write_statement(&stmt) => stmt,
1680 Some(_stmt) => {
1681 return Ok(None);
1682 }
1683 None => {
1684 return Ok(None);
1685 }
1686 };
1687
1688 Coordinator::verify_portal(
1693 &catalog,
1694 self.session.as_mut().expect("SessionClient invariant"),
1695 portal_name,
1696 )?;
1697
1698 let (params, logging_info, lifecycle_timestamps) = {
1699 let portal = self
1700 .session
1701 .as_ref()
1702 .expect("SessionClient invariant")
1703 .get_portal_unverified(portal_name)
1704 .expect("verified above");
1705 (
1706 portal.parameters.clone(),
1707 Arc::clone(&portal.logging),
1708 portal.lifecycle_timestamps.clone(),
1709 )
1710 };
1711
1712 logging.take_over(
1716 &self.peek_client,
1717 self.session.as_mut().expect("SessionClient invariant"),
1718 Some(&stmt),
1719 ¶ms,
1720 &logging_info,
1721 &catalog,
1722 lifecycle_timestamps,
1723 TakeOver::StatementToRun,
1724 );
1725
1726 {
1738 let session = self.session.as_ref().expect("SessionClient invariant");
1739 let contains_ops = session.transaction().contains_ops();
1747 match session.transaction() {
1748 TransactionStatus::Default | TransactionStatus::Failed(_) => {}
1749 TransactionStatus::Started(_) if !contains_ops => {}
1750 TransactionStatus::Started(_)
1751 | TransactionStatus::InTransactionImplicit(_)
1752 | TransactionStatus::InTransaction(_) => {
1753 let constant_insert = matches!(
1754 &*stmt,
1755 Statement::Insert(InsertStatement {
1756 source, returning, ..
1757 }) if returning.is_empty() && ConstantVisitor::insert_source(source)
1758 );
1759 if !constant_insert {
1760 return Err(prohibited_in_transaction(&stmt));
1761 }
1762 }
1763 }
1764 }
1765
1766 let (plan, target_cluster, resolved_ids, sql_impl_ids) = {
1767 let session = self.session.as_mut().expect("SessionClient invariant");
1768 let conn_catalog = catalog.for_session(session);
1769 let (stmt, resolved_ids) = mz_sql::names::resolve(&conn_catalog, (*stmt).clone())?;
1770 let pcx = session.pcx();
1771 let (plan, sql_impl_ids) =
1772 mz_sql::plan::plan(Some(pcx), &conn_catalog, stmt, ¶ms, &resolved_ids)?;
1773
1774 let target_cluster = match session.transaction().cluster() {
1775 Some(cluster_id) => crate::coord::TargetCluster::Transaction(cluster_id),
1776 None => crate::coord::catalog_serving::auto_run_on_catalog_server(
1777 &conn_catalog,
1778 session,
1779 &plan,
1780 ),
1781 };
1782
1783 (plan, target_cluster, resolved_ids, sql_impl_ids)
1784 };
1785
1786 if self.peek_client.read_only {
1793 return Err(AdapterError::ReadOnly);
1794 }
1795
1796 let (target_cluster_id, target_cluster_name) = {
1802 let session = self.session.as_ref().expect("SessionClient invariant");
1803 match catalog.resolve_target_cluster(target_cluster.clone(), session) {
1804 Ok(cluster) => (Some(cluster.id), Some(cluster.name.clone())),
1805 Err(_) => (None, None),
1806 }
1807 };
1808
1809 if let (Some(logging_id), Some(cluster_id), Some(cluster_name)) =
1812 (logging.id(), target_cluster_id, target_cluster_name.clone())
1813 {
1814 self.peek_client
1815 .log_set_cluster(logging_id, cluster_id, cluster_name);
1816 }
1817
1818 {
1819 let session = self.session.as_ref().expect("SessionClient invariant");
1820 let conn_catalog = catalog.for_session(session);
1821 if let Some(cluster_name) = &target_cluster_name {
1822 crate::coord::catalog_serving::check_cluster_restrictions(
1823 cluster_name,
1824 &conn_catalog,
1825 &plan,
1826 )?;
1827 }
1828 if let Err(e) = mz_sql::rbac::check_plan(
1829 &conn_catalog,
1830 None,
1831 session,
1832 &plan,
1833 target_cluster_id,
1834 &resolved_ids,
1835 &sql_impl_ids,
1836 ) {
1837 return Err(e.into());
1838 }
1839 }
1840
1841 {
1845 let session = self.session.as_mut().expect("SessionClient invariant");
1846 if let Some(wait_future) =
1847 crate::coord::appends::waiting_on_startup_appends(&catalog, session, &plan)
1848 {
1849 wait_future.await;
1850 }
1851 }
1852
1853 {
1858 let session = self.session.as_ref().expect("SessionClient invariant");
1859 if session.transaction().is_in_multi_statement_transaction()
1860 && !session.transaction().allows_writes()
1861 {
1862 return Err(AdapterError::ReadOnlyTransaction);
1863 }
1864 if session
1865 .vars()
1866 .transaction_isolation()
1867 .is_bounded_staleness()
1868 {
1869 return Err(AdapterError::BoundedStalenessReadOnly);
1870 }
1871 }
1872
1873 let rtw_plan = match plan {
1875 Plan::ReadThenWrite(rtw_plan) => rtw_plan,
1876 Plan::Insert(insert_plan) => {
1877 let has_read_deps = !insert_plan.values.depends_on().is_empty();
1897
1898 if !has_read_deps {
1899 let optimized_mir = if insert_plan.values.as_const().is_some() {
1900 let expr = insert_plan
1902 .values
1903 .clone()
1904 .lower(catalog.system_config(), None)?;
1905 mz_expr::OptimizedMirRelationExpr(expr)
1906 } else {
1907 let optimizer_config =
1912 optimize::OptimizerConfig::from(catalog.system_config());
1913 let session = self.session.as_ref().expect("SessionClient invariant");
1914 let prep = ExprPrepOneShot {
1915 logical_time: EvalTime::NotAvailable,
1916 session,
1917 catalog_state: catalog.state(),
1918 };
1919 let mut optimizer =
1920 optimize::view::Optimizer::new_with_prep(optimizer_config, None, prep);
1921 match optimizer.optimize(insert_plan.values.clone()) {
1922 Ok(expr) => expr,
1923 Err(OptimizerError::UncallableFunction {
1924 func: UnmaterializableFunc::MzNow,
1925 ..
1926 }) => {
1927 let expr = insert_plan
1930 .values
1931 .clone()
1932 .lower(catalog.system_config(), None)?;
1933 mz_expr::OptimizedMirRelationExpr(expr)
1934 }
1935 Err(e) => return Err(e.into()),
1936 }
1937 };
1938
1939 let inner_mir = optimized_mir.into_inner();
1940 if inner_mir.as_const().is_some() && insert_plan.returning.is_empty() {
1941 let session = self.session.as_mut().expect("SessionClient invariant");
1942 let result = Coordinator::insert_constant(
1943 &catalog,
1944 session,
1945 insert_plan.id,
1946 inner_mir,
1947 );
1948
1949 return Ok(Some(result?));
1950 }
1951 }
1952
1953 let desc_arity = match catalog.try_get_entry(&insert_plan.id) {
1954 Some(table) => {
1955 let desc = table
1956 .relation_desc_latest()
1957 .ok_or_else(|| AdapterError::Internal("table has no desc".into()))?;
1958 desc.arity()
1959 }
1960 None => {
1961 return Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
1962 kind: mz_catalog::memory::error::ErrorKind::Sql(
1963 mz_sql::catalog::CatalogError::UnknownItem(
1964 insert_plan.id.to_string(),
1965 ),
1966 ),
1967 }));
1968 }
1969 };
1970
1971 let finishing = RowSetFinishing {
1972 order_by: vec![],
1973 limit: None,
1974 offset: 0,
1975 project: (0..desc_arity).collect(),
1976 };
1977
1978 ReadThenWritePlan {
1979 id: insert_plan.id,
1980 selection: insert_plan.values,
1981 finishing,
1982 assignments: BTreeMap::new(),
1983 kind: MutationKind::Insert,
1984 returning: insert_plan.returning,
1985 }
1986 }
1987 _ => {
1988 return Err(AdapterError::Internal(
1989 "unexpected plan type for mutation".into(),
1990 ));
1991 }
1992 };
1993
1994 {
2005 let session = self.session.as_ref().expect("SessionClient invariant");
2006 let in_transaction = session
2007 .transaction()
2008 .may_share_transaction_with_other_statements();
2009 let depends_on = rtw_plan.selection.depends_on();
2010 if in_transaction && !depends_on.is_empty() {
2011 if contains_mz_now(&rtw_plan) {
2018 return Err(AdapterError::Unsupported(
2019 "calls to mz_now in write statements",
2020 ));
2021 }
2022 validate_selection_dependencies(&catalog, &depends_on, DependencyPolicy::UserDml)?;
2023 return Err(prohibited_in_transaction(&stmt));
2024 }
2025 }
2026
2027 let session = self.session.as_mut().expect("SessionClient invariant");
2028 self.peek_client
2029 .session_read_then_write(
2030 session,
2031 rtw_plan,
2032 target_cluster,
2033 &catalog,
2034 logging.id(),
2035 attempt_state,
2036 )
2037 .await
2038 .map(Some)
2039 }
2040}
2041
2042fn is_read_then_write_statement(stmt: &Statement<Raw>) -> bool {
2048 matches!(
2049 stmt,
2050 Statement::Delete(_) | Statement::Update(_) | Statement::Insert(_)
2051 )
2052}
2053
2054fn prohibited_in_transaction(stmt: &Statement<Raw>) -> AdapterError {
2059 let op = if StatementKind::from(stmt).is_sensitive() {
2060 stmt.to_ast_string_redacted()
2061 } else {
2062 stmt.to_string()
2063 };
2064 AdapterError::OperationProhibitsTransaction(op)
2065}
2066
2067impl Drop for SessionClient {
2068 fn drop(&mut self) {
2069 if let Some(session) = self.session.take() {
2073 if let Some(inner) = &self.inner {
2076 inner.send(Command::Terminate {
2077 conn_id: session.conn_id().clone(),
2078 tx: None,
2079 })
2080 }
2081 }
2082 }
2083}
2084
2085pub fn redact_sql_for_logging(sql: &str) -> String {
2093 match mz_sql_parser::parser::parse_statements_with_limit(sql) {
2094 Ok(Ok(stmts)) => truncate_sql_for_logging(
2095 stmts
2096 .into_iter()
2097 .map(|stmt| stmt.ast.to_ast_string_redacted())
2098 .join("; "),
2099 ),
2100 Ok(Err(_)) => format!("<unparseable ({} bytes)>", sql.len()),
2101 Err(_) => format!("<too large ({} bytes)>", sql.len()),
2102 }
2103}
2104
2105const MAX_LOGGED_SQL_LEN: usize = 8 * 1024;
2112
2113pub fn truncate_sql_for_logging(sql: String) -> String {
2116 if sql.len() <= MAX_LOGGED_SQL_LEN {
2117 return sql;
2118 }
2119 let end = sql.floor_char_boundary(MAX_LOGGED_SQL_LEN);
2120 format!("{}... <truncated from {} bytes>", &sql[..end], sql.len())
2121}
2122
2123#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
2124pub enum TimeoutType {
2125 IdleInTransactionSession(TransactionId),
2126}
2127
2128impl Display for TimeoutType {
2129 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2130 match self {
2131 TimeoutType::IdleInTransactionSession(txn_id) => {
2132 writeln!(f, "Idle in transaction session for transaction '{txn_id}'")
2133 }
2134 }
2135 }
2136}
2137
2138impl From<TimeoutType> for AdapterError {
2139 fn from(timeout: TimeoutType) -> Self {
2140 match timeout {
2141 TimeoutType::IdleInTransactionSession(_) => {
2142 AdapterError::IdleInTransactionSessionTimeout
2143 }
2144 }
2145 }
2146}
2147
2148struct Timeout {
2149 tx: mpsc::UnboundedSender<TimeoutType>,
2150 rx: mpsc::UnboundedReceiver<TimeoutType>,
2151 active_timeouts: BTreeMap<TimeoutType, AbortOnDropHandle<()>>,
2152}
2153
2154impl Timeout {
2155 fn new() -> Self {
2156 let (tx, rx) = mpsc::unbounded_channel();
2157 Timeout {
2158 tx,
2159 rx,
2160 active_timeouts: BTreeMap::new(),
2161 }
2162 }
2163
2164 async fn recv(&mut self) -> Option<TimeoutType> {
2173 self.rx.recv().await
2174 }
2175
2176 fn add_timeout(&mut self, timeout: TimeoutType, duration: Duration) {
2177 let tx = self.tx.clone();
2178 let timeout_key = timeout.clone();
2179 let handle = mz_ore::task::spawn(|| format!("{timeout_key}"), async move {
2180 tokio::time::sleep(duration).await;
2181 let _ = tx.send(timeout);
2182 })
2183 .abort_on_drop();
2184 self.active_timeouts.insert(timeout_key, handle);
2185 }
2186
2187 fn remove_timeout(&mut self, timeout: &TimeoutType) {
2188 self.active_timeouts.remove(timeout);
2189
2190 let mut timeouts = Vec::new();
2192 while let Ok(pending_timeout) = self.rx.try_recv() {
2193 if timeout != &pending_timeout {
2194 timeouts.push(pending_timeout);
2195 }
2196 }
2197 for pending_timeout in timeouts {
2198 self.tx.send(pending_timeout).expect("rx is in this struct");
2199 }
2200 }
2201}
2202
2203#[derive(Debug)]
2206pub struct SettledStatement {
2207 pub reverted: BTreeMap<&'static str, String>,
2210}
2211
2212#[derive(Derivative)]
2216#[derivative(Debug)]
2217pub struct RecordFirstRowStream {
2218 #[derivative(Debug = "ignore")]
2220 pub rows: Box<dyn Stream<Item = PeekResponseUnary> + Unpin + Send + Sync>,
2221 pub execute_started: Instant,
2223 pub time_to_first_row_seconds: Histogram,
2226 pub saw_rows: bool,
2228 pub recorded_first_row_instant: Option<Instant>,
2230 pub no_more_rows: bool,
2232 pub metric_recorded: bool,
2234 execution_time: Option<ExecutionTime>,
2235 execution_time_reported: bool,
2236}
2237
2238impl RecordFirstRowStream {
2239 pub fn new(
2241 rows: Box<dyn Stream<Item = PeekResponseUnary> + Unpin + Send + Sync>,
2242 execute_started: Instant,
2243 client: &SessionClient,
2244 instance_id: Option<ComputeInstanceId>,
2245 strategy: Option<StatementExecutionStrategy>,
2246 ) -> Self {
2247 let histogram = Self::histogram(client, instance_id, strategy);
2248 Self {
2249 rows,
2250 execute_started,
2251 time_to_first_row_seconds: histogram,
2252 saw_rows: false,
2253 recorded_first_row_instant: None,
2254 no_more_rows: false,
2255 metric_recorded: false,
2256 execution_time: None,
2257 execution_time_reported: false,
2258 }
2259 }
2260
2261 fn histogram(
2262 client: &SessionClient,
2263 instance_id: Option<ComputeInstanceId>,
2264 strategy: Option<StatementExecutionStrategy>,
2265 ) -> Histogram {
2266 let session = client.session.as_ref().expect("session invariant");
2267 let isolation_level = *session.vars().transaction_isolation();
2268 let name_hint = ApplicationNameHint::from_str(session.application_name());
2269
2270 client
2271 .inner()
2272 .metrics()
2273 .by_cluster
2274 .time_to_first_row_seconds(instance_id, isolation_level, strategy, name_hint)
2275 }
2276
2277 pub fn record(
2280 execute_started: Instant,
2281 client: &SessionClient,
2282 instance_id: Option<ComputeInstanceId>,
2283 strategy: Option<StatementExecutionStrategy>,
2284 ) {
2285 Self::histogram(client, instance_id, strategy)
2286 .observe(execute_started.elapsed().as_secs_f64());
2287 }
2288
2289 pub async fn recv(&mut self) -> Option<PeekResponseUnary> {
2290 let mut msg = self.rows.next().await;
2291 if !self.saw_rows && matches!(msg, Some(PeekResponseUnary::Rows(_))) {
2292 self.saw_rows = true;
2293 self.time_to_first_row_seconds
2294 .observe(self.execute_started.elapsed().as_secs_f64());
2295 self.recorded_first_row_instant = Some(Instant::now());
2296 }
2297 if msg.is_none() {
2298 self.no_more_rows = true;
2299 }
2300 if self.execution_time.is_none() && !self.execution_time_reported {
2301 let kind = match &mut msg {
2302 Some(PeekResponseUnary::Rows(rows)) => {
2305 rows.peek().is_some().then_some(ExecutionTimeKind::FirstRow)
2306 }
2307 None => Some(ExecutionTimeKind::EmptyResult),
2308 _ => None,
2309 };
2310 self.execution_time = kind.map(|kind| ExecutionTime {
2311 kind,
2312 elapsed: self.execute_started.elapsed(),
2313 });
2314 }
2315 msg
2316 }
2317
2318 pub fn without_execution_time(mut self) -> Self {
2320 self.execution_time = None;
2321 self.execution_time_reported = true;
2322 self
2323 }
2324
2325 pub fn take_execution_time(&mut self) -> Option<ExecutionTime> {
2328 self.execution_time_reported = true;
2329 self.execution_time.take()
2330 }
2331}
2332
2333#[cfg(test)]
2334mod tests {
2335 use super::*;
2336
2337 #[mz_ore::test]
2338 fn truncate_sql_for_logging_caps_length() {
2339 let short = "SELECT 1".to_string();
2340 assert_eq!(truncate_sql_for_logging(short.clone()), short);
2341
2342 let exact = "x".repeat(MAX_LOGGED_SQL_LEN);
2343 assert_eq!(truncate_sql_for_logging(exact.clone()), exact);
2344
2345 let long = format!(
2348 "{}é{}",
2349 "x".repeat(MAX_LOGGED_SQL_LEN - 1),
2350 "y".repeat(1000)
2351 );
2352 let truncated = truncate_sql_for_logging(long.clone());
2353 assert_eq!(
2354 truncated,
2355 format!(
2356 "{}... <truncated from {} bytes>",
2357 "x".repeat(MAX_LOGGED_SQL_LEN - 1),
2358 long.len()
2359 )
2360 );
2361 }
2362}