1#![warn(missing_docs)]
13
14use std::collections::BTreeMap;
15use std::collections::btree_map::Entry;
16use std::future::Future;
17use std::mem;
18use std::net::IpAddr;
19use std::sync::Arc;
20
21use chrono::{DateTime, Utc};
22use derivative::Derivative;
23use mz_adapter_types::connection::ConnectionId;
24use mz_auth::AuthenticatorKind;
25use mz_auth::user::ExternalUserMetadata;
26use mz_build_info::{BuildInfo, DUMMY_BUILD_INFO};
27use mz_controller_types::ClusterId;
28use mz_ore::metrics::{MetricsFutureExt, MetricsRegistry};
29use mz_ore::now::{EpochMillis, NowFn};
30use mz_pgwire_common::Format;
31use mz_repr::role_id::RoleId;
32use mz_repr::user::InternalUserMetadata;
33use mz_repr::{CatalogItemId, Datum, Row, RowIterator, SqlScalarType, Timestamp};
34use mz_sql::ast::{AstInfo, Raw, Statement, TransactionAccessMode};
35use mz_sql::plan::{Params, PlanContext, QueryWhen, StatementDesc};
36use mz_sql::session::metadata::SessionMetadata;
37use mz_sql::session::user::{
38 INTERNAL_USER_NAME_TO_DEFAULT_CLUSTER, RoleMetadata, SYSTEM_USER, User,
39};
40use mz_sql::session::vars::IsolationLevel;
41pub use mz_sql::session::vars::{
42 DEFAULT_DATABASE_NAME, EndTransactionAction, SERVER_MAJOR_VERSION, SERVER_MINOR_VERSION,
43 SERVER_PATCH_VERSION, SessionVars, Var,
44};
45use mz_sql_parser::ast::TransactionIsolationLevel;
46use mz_storage_client::client::TableData;
47use mz_storage_types::sources::Timeline;
48use qcell::{QCell, QCellOwner};
49use timely::progress::Timestamp as _;
50use tokio::sync::mpsc::{self, UnboundedSender};
51use tokio::sync::watch;
52use uuid::Uuid;
53
54use crate::AdapterNotice;
55use crate::ExecutionTime;
56use crate::catalog::CatalogState;
57use crate::client::RecordFirstRowStream;
58use crate::coord::ExplainContext;
59use crate::coord::appends::BuiltinTableAppendNotify;
60use crate::coord::in_memory_oracle::InMemoryTimestampOracle;
61use crate::coord::peek::PeekResponseUnary;
62use crate::coord::timestamp_selection::{TimestampContext, TimestampDetermination};
63use crate::error::AdapterError;
64use crate::metrics::{Metrics, SessionMetrics};
65use crate::notice::ExecutionTimeKind;
66use crate::statement_logging::PreparedStatementLoggingInfo;
67use mz_catalog::durable::Snapshot;
68
69pub(crate) const DUMMY_CONNECTION_ID: ConnectionId = ConnectionId::Static(0);
70
71#[derive(Derivative)]
73#[derivative(Debug)]
74pub struct Session {
75 conn_id: ConnectionId,
76 uuid: Uuid,
79 prepared_statements: BTreeMap<String, PreparedStatement>,
80 portals: BTreeMap<String, Portal>,
81 transaction: TransactionStatus,
82 pcx: Option<PlanContext>,
83 metrics: SessionMetrics,
84 #[derivative(Debug = "ignore")]
85 builtin_updates: Option<BuiltinTableAppendNotify>,
86
87 role_metadata: Option<RoleMetadata>,
100 client_ip: Option<IpAddr>,
101 vars: SessionVars,
102 notices_tx: mpsc::UnboundedSender<AdapterNotice>,
103 notices_rx: mpsc::UnboundedReceiver<AdapterNotice>,
104 next_transaction_id: TransactionId,
105 secret_key: u32,
106 external_metadata_rx: Option<watch::Receiver<ExternalUserMetadata>>,
107 #[derivative(Debug = "ignore")]
119 qcell_owner: QCellOwner,
120 session_oracles: BTreeMap<Timeline, InMemoryTimestampOracle>,
121 state_revision: u64,
126}
127
128impl SessionMetadata for Session {
129 fn conn_id(&self) -> &ConnectionId {
130 &self.conn_id
131 }
132
133 fn client_ip(&self) -> Option<&IpAddr> {
134 self.client_ip.as_ref()
135 }
136
137 fn pcx(&self) -> &PlanContext {
138 &self
139 .transaction()
140 .inner()
141 .expect("no active transaction")
142 .pcx
143 }
144
145 fn role_metadata(&self) -> &RoleMetadata {
146 self.role_metadata
147 .as_ref()
148 .expect("role_metadata invariant violated")
149 }
150
151 fn vars(&self) -> &SessionVars {
152 &self.vars
153 }
154}
155
156#[derive(Debug)]
159pub struct SessionMeta {
160 conn_id: ConnectionId,
161 client_ip: Option<IpAddr>,
162 pcx: PlanContext,
163 role_metadata: RoleMetadata,
164 vars: SessionVars,
165}
166
167impl SessionMetadata for SessionMeta {
168 fn vars(&self) -> &SessionVars {
169 &self.vars
170 }
171
172 fn conn_id(&self) -> &ConnectionId {
173 &self.conn_id
174 }
175
176 fn client_ip(&self) -> Option<&IpAddr> {
177 self.client_ip.as_ref()
178 }
179
180 fn pcx(&self) -> &PlanContext {
181 &self.pcx
182 }
183
184 fn role_metadata(&self) -> &RoleMetadata {
185 &self.role_metadata
186 }
187}
188
189#[derive(Debug, Clone)]
191pub struct SessionConfig {
192 pub conn_id: ConnectionId,
196 pub uuid: Uuid,
201 pub client_ip: Option<IpAddr>,
203 pub user: String,
205 pub external_metadata_rx: Option<watch::Receiver<ExternalUserMetadata>>,
208 pub helm_chart_version: Option<String>,
210 pub authenticator_kind: AuthenticatorKind,
212 pub groups: Option<Vec<String>>,
214}
215
216impl Session {
217 pub(crate) fn new(
219 build_info: &'static BuildInfo,
220 config: SessionConfig,
221 metrics: SessionMetrics,
222 ) -> Session {
223 assert_ne!(config.conn_id, DUMMY_CONNECTION_ID);
224 Self::new_internal(build_info, config, metrics)
225 }
226
227 pub fn meta(&self) -> SessionMeta {
230 SessionMeta {
231 conn_id: self.conn_id().clone(),
232 client_ip: self.client_ip().copied(),
233 pcx: self.pcx().clone(),
234 role_metadata: self.role_metadata().clone(),
235 vars: self.vars.clone(),
236 }
237
238 }
240
241 pub(crate) fn mint_logging<A: AstInfo>(
251 &self,
252 raw_sql: String,
253 stmt: Option<&Statement<A>>,
254 now: EpochMillis,
255 ) -> Arc<QCell<PreparedStatementLoggingInfo>> {
256 Arc::new(QCell::new(
257 &self.qcell_owner,
258 PreparedStatementLoggingInfo::still_to_log(
259 raw_sql,
260 stmt,
261 now,
262 "".to_string(),
263 self.uuid,
264 false,
265 ),
266 ))
267 }
268
269 pub(crate) fn qcell_ro<'a, T2: 'a>(&'a self, cell: &'a Arc<QCell<T2>>) -> &'a T2 {
270 self.qcell_owner.ro(&*cell)
271 }
272
273 pub(crate) fn qcell_rw<'a, T2: 'a>(&'a mut self, cell: &'a Arc<QCell<T2>>) -> &'a mut T2 {
274 self.qcell_owner.rw(&*cell)
275 }
276
277 pub fn uuid(&self) -> Uuid {
280 self.uuid
281 }
282
283 pub fn dummy() -> Session {
288 let registry = MetricsRegistry::new();
289 let metrics = Metrics::register_into(®istry);
290 let metrics = metrics.session_metrics();
291 let mut dummy = Self::new_internal(
292 &DUMMY_BUILD_INFO,
293 SessionConfig {
294 conn_id: DUMMY_CONNECTION_ID,
295 uuid: Uuid::new_v4(),
296 user: SYSTEM_USER.name.clone(),
297 client_ip: None,
298 external_metadata_rx: None,
299 helm_chart_version: None,
300 authenticator_kind: AuthenticatorKind::None,
301 groups: None,
302 },
303 metrics,
304 );
305 dummy.initialize_role_metadata(RoleId::User(0));
306 dummy
307 }
308
309 fn new_internal(
310 build_info: &'static BuildInfo,
311 SessionConfig {
312 conn_id,
313 uuid,
314 user,
315 client_ip,
316 mut external_metadata_rx,
317 helm_chart_version,
318 authenticator_kind,
319 groups,
320 }: SessionConfig,
321 metrics: SessionMetrics,
322 ) -> Session {
323 let (notices_tx, notices_rx) = mpsc::unbounded_channel();
324 let default_cluster = INTERNAL_USER_NAME_TO_DEFAULT_CLUSTER.get(&user);
325 let user = User {
326 name: user,
327 internal_metadata: None,
328 external_metadata: external_metadata_rx
329 .as_mut()
330 .map(|rx| rx.borrow_and_update().clone()),
331 authenticator_kind: Some(authenticator_kind),
332 groups,
333 };
334 let mut vars = SessionVars::new_unchecked(build_info, user, helm_chart_version);
335 if let Some(default_cluster) = default_cluster {
336 vars.set_cluster(default_cluster.clone());
337 }
338 Session {
339 conn_id,
340 uuid,
341 transaction: TransactionStatus::Default,
342 pcx: None,
343 metrics,
344 builtin_updates: None,
345 prepared_statements: BTreeMap::new(),
346 portals: BTreeMap::new(),
347 role_metadata: None,
348 client_ip,
349 vars,
350 notices_tx,
351 notices_rx,
352 next_transaction_id: 0,
353 secret_key: rand::random(),
354 external_metadata_rx,
355 qcell_owner: QCellOwner::new(),
356 session_oracles: BTreeMap::new(),
357 state_revision: 0,
358 }
359 }
360
361 pub fn secret_key(&self) -> u32 {
363 self.secret_key
364 }
365
366 fn new_pcx(&self, mut wall_time: DateTime<Utc>) -> PlanContext {
367 if let Some(mock_time) = self.vars().unsafe_new_transaction_wall_time() {
368 wall_time = *mock_time;
369 }
370 PlanContext::new(wall_time)
371 }
372
373 pub fn start_transaction(
376 &mut self,
377 wall_time: DateTime<Utc>,
378 access: Option<TransactionAccessMode>,
379 isolation_level: Option<TransactionIsolationLevel>,
380 ) -> Result<(), AdapterError> {
381 if let Some(txn) = self.transaction.inner() {
383 let read_write_prohibited = match txn.ops {
387 TransactionOps::Peeks { .. } | TransactionOps::Subscribe => {
388 txn.access == Some(TransactionAccessMode::ReadOnly)
389 }
390 TransactionOps::None
391 | TransactionOps::Writes(_)
392 | TransactionOps::SingleStatement { .. }
393 | TransactionOps::DDL { .. } => false,
394 };
395
396 if read_write_prohibited && access == Some(TransactionAccessMode::ReadWrite) {
397 return Err(AdapterError::ReadWriteUnavailable);
398 }
399 }
400
401 match std::mem::take(&mut self.transaction) {
402 TransactionStatus::Default => {
403 let id = self.next_transaction_id;
404 self.next_transaction_id = self.next_transaction_id.wrapping_add(1);
405 self.transaction = TransactionStatus::InTransaction(Transaction {
406 completion_owner: TransactionCompletionOwner::Coordinator,
407 pcx: self.new_pcx(wall_time),
408 ops: TransactionOps::None,
409 pending_ddl_inspections: Vec::new(),
410 contains_explain: false,
411 access,
412 id,
413 });
414 }
415 TransactionStatus::Started(mut txn)
416 | TransactionStatus::InTransactionImplicit(mut txn)
417 | TransactionStatus::InTransaction(mut txn) => {
418 if access.is_some() {
419 txn.access = access;
420 }
421 self.transaction = TransactionStatus::InTransaction(txn);
422 }
423 TransactionStatus::Failed(_) => unreachable!(),
424 };
425
426 if let Some(isolation_level) = isolation_level {
427 self.vars
428 .set_local_transaction_isolation(isolation_level.into());
429 }
430
431 Ok(())
432 }
433
434 pub fn start_transaction_implicit(&mut self, wall_time: DateTime<Utc>, stmts: usize) {
437 if let TransactionStatus::Default = self.transaction {
438 let id = self.next_transaction_id;
439 self.next_transaction_id = self.next_transaction_id.wrapping_add(1);
440 let txn = Transaction {
441 completion_owner: TransactionCompletionOwner::Session,
442 pcx: self.new_pcx(wall_time),
443 ops: TransactionOps::None,
444 pending_ddl_inspections: Vec::new(),
445 contains_explain: false,
446 access: None,
447 id,
448 };
449 match stmts {
450 1 => self.transaction = TransactionStatus::Started(txn),
451 n if n > 1 => self.transaction = TransactionStatus::InTransactionImplicit(txn),
452 _ => {}
453 }
454 }
455 }
456
457 pub fn start_transaction_single_stmt(&mut self, wall_time: DateTime<Utc>) {
459 self.start_transaction_implicit(wall_time, 1);
460 }
461
462 #[must_use]
472 pub fn clear_transaction(&mut self) -> TransactionStatus {
473 self.portals.clear();
474 self.pcx = None;
475 self.state_revision += 1;
476 mem::take(&mut self.transaction)
477 }
478
479 pub(crate) fn require_coordinator_completion(&mut self) {
482 if let Some(txn) = self.transaction.inner_mut() {
483 txn.completion_owner = TransactionCompletionOwner::Coordinator;
484 }
485 }
486
487 pub(crate) fn read_only_completion(
489 &self,
490 mut action: EndTransactionAction,
491 ) -> Option<ReadOnlyCompletion> {
492 let txn = self.transaction.inner()?;
493 if txn.completion_owner != TransactionCompletionOwner::Session {
494 return None;
495 }
496 let timestamp = match &txn.ops {
497 TransactionOps::None => None,
498 TransactionOps::Peeks {
499 determination,
500 requires_linearization,
501 ..
502 } => matches!(requires_linearization, RequireLinearization::Required)
503 .then(|| determination.timestamp_context.clone()),
504 TransactionOps::Writes(_)
505 | TransactionOps::Subscribe
506 | TransactionOps::SingleStatement { .. }
507 | TransactionOps::DDL { .. } => return None,
508 };
509 if matches!(self.transaction, TransactionStatus::Failed(_)) {
510 action = EndTransactionAction::Rollback;
511 }
512 Some(ReadOnlyCompletion {
513 action,
514 timestamp: if action == EndTransactionAction::Commit {
515 timestamp
516 } else {
517 None
518 },
519 })
520 }
521
522 pub fn fail_transaction(mut self) -> Self {
524 match self.transaction {
525 TransactionStatus::Default => unreachable!(),
526 TransactionStatus::Started(txn)
527 | TransactionStatus::InTransactionImplicit(txn)
528 | TransactionStatus::InTransaction(txn) => {
529 self.transaction = TransactionStatus::Failed(txn);
530 }
531 TransactionStatus::Failed(_) => {}
532 };
533 self
534 }
535
536 pub fn transaction(&self) -> &TransactionStatus {
538 &self.transaction
539 }
540
541 pub fn transaction_mut(&mut self) -> &mut TransactionStatus {
543 &mut self.transaction
544 }
545
546 pub fn transaction_code(&self) -> TransactionCode {
548 self.transaction().into()
549 }
550
551 pub(crate) fn retain_catalog_result(
553 &mut self,
554 command: Arc<crate::catalog::command::CatalogResultCommand>,
555 ) {
556 self.retain_ddl_inspection(DdlInspection::CatalogResult(command));
557 }
558
559 fn retain_ddl_inspection(&mut self, inspection: DdlInspection) {
560 if !self.transaction().can_retain_ddl_inspections() {
561 return;
562 }
563 let txn = self
564 .transaction_mut()
565 .inner_mut()
566 .expect("active transaction");
567 match &mut txn.ops {
568 TransactionOps::DDL { commands, .. } => commands.push(inspection.into_command()),
569 _ => txn.pending_ddl_inspections.push(inspection),
570 }
571 }
572
573 pub(crate) fn retain_description(
575 &mut self,
576 statement: mz_sql::ast::Statement<mz_sql::ast::Raw>,
577 param_types: Vec<Option<mz_repr::SqlScalarType>>,
578 expected: mz_sql::plan::StatementDesc,
579 ) {
580 if !self.transaction().can_retain_ddl_inspections()
581 || (expected.relation_desc.is_none() && expected.param_types.is_empty())
582 {
583 return;
584 }
585 let mut described = &statement;
588 while let mz_sql::ast::Statement::Declare(declare) = described {
589 described = &declare.stmt;
590 }
591 if matches!(
592 described,
593 mz_sql::ast::Statement::Execute(_) | mz_sql::ast::Statement::Fetch(_)
594 ) {
595 return;
596 }
597 let command = crate::catalog::command::DescriptionCommand::new(
598 statement,
599 param_types,
600 self.meta(),
601 expected,
602 );
603 self.retain_ddl_inspection(DdlInspection::Description(Arc::new(command)));
604 }
605
606 pub fn add_transaction_ops(&mut self, add_ops: TransactionOps) -> Result<(), AdapterError> {
608 self.transaction.add_ops(add_ops)
609 }
610
611 pub fn retain_notice_transmitter(&self) -> UnboundedSender<AdapterNotice> {
613 self.notices_tx.clone()
614 }
615
616 pub fn add_notice(&self, notice: AdapterNotice) {
618 self.add_notices([notice])
619 }
620
621 pub fn add_notices(&self, notices: impl IntoIterator<Item = AdapterNotice>) {
623 for notice in notices {
624 let _ = self.notices_tx.send(notice);
625 }
626 }
627
628 pub async fn recv_notice(&mut self) -> AdapterNotice {
632 loop {
634 let notice = self
635 .notices_rx
636 .recv()
637 .await
638 .expect("Session also holds a sender, so recv won't ever return None");
639 match self.notice_filter(notice) {
640 Some(notice) => return notice,
641 None => continue,
642 }
643 }
644 }
645
646 pub fn drain_notices(&mut self) -> Vec<AdapterNotice> {
648 let mut notices = Vec::new();
649 while let Ok(notice) = self.notices_rx.try_recv() {
650 if let Some(notice) = self.notice_filter(notice) {
651 notices.push(notice);
652 }
653 }
654 notices
655 }
656
657 pub fn execution_time_notice(&self, time: ExecutionTime) -> Option<AdapterNotice> {
659 if !self.vars.emit_execution_time_notice() {
660 return None;
661 }
662 self.notice_filter(AdapterNotice::ExecutionTime(time))
663 }
664
665 pub fn maybe_mark_staged(&self, time: ExecutionTime) -> ExecutionTime {
671 let staged = self
672 .transaction()
673 .inner()
674 .is_some_and(|txn| txn.ops.stages_work());
675 if staged {
676 ExecutionTime {
677 kind: ExecutionTimeKind::Staged,
678 ..time
679 }
680 } else {
681 time
682 }
683 }
684
685 fn notice_filter(&self, notice: AdapterNotice) -> Option<AdapterNotice> {
687 let minimum_client_severity = self.vars.client_min_messages();
689 let sev = notice.severity();
690 if !minimum_client_severity.should_output_to_client(&sev) {
691 return None;
692 }
693 if let AdapterNotice::ClusterReplicaStatusChanged { cluster, .. } = ¬ice {
695 if cluster != self.vars.cluster() {
696 return None;
697 }
698 }
699 Some(notice)
700 }
701
702 pub fn clear_transaction_ops(&mut self) {
705 if let Some(txn) = self.transaction.inner_mut() {
706 txn.ops = TransactionOps::None;
707 }
708 }
709
710 pub fn get_transaction_timestamp_determination(&self) -> Option<TimestampDetermination> {
715 match self.transaction.inner() {
716 Some(Transaction {
717 pcx: _,
718 ops: TransactionOps::Peeks { determination, .. },
719 access: _,
720 id: _,
721 pending_ddl_inspections: _,
722 contains_explain: _,
723 completion_owner: _,
724 }) => Some(determination.clone()),
725 _ => None,
726 }
727 }
728
729 pub fn contains_read_timestamp(&self) -> bool {
731 matches!(
732 self.transaction.inner(),
733 Some(Transaction {
734 pcx: _,
735 ops: TransactionOps::Peeks {
736 determination: TimestampDetermination {
737 timestamp_context: TimestampContext::TimelineTimestamp { .. },
738 ..
739 },
740 ..
741 },
742 access: _,
743 id: _,
744 pending_ddl_inspections: _,
745 contains_explain: _,
746 completion_owner: _,
747 })
748 )
749 }
750
751 pub fn set_prepared_statement(
753 &mut self,
754 name: String,
755 stmt: Option<Statement<Raw>>,
756 raw_sql: String,
757 desc: StatementDesc,
758 state_revision: StateRevision,
759 now: EpochMillis,
760 ) {
761 let state_revision = self.advance_state_revision_for_insert(state_revision);
762 let logging = PreparedStatementLoggingInfo::still_to_log(
763 raw_sql,
764 stmt.as_ref(),
765 now,
766 name.clone(),
767 self.uuid,
768 false,
769 );
770 let statement = PreparedStatement {
771 stmt,
772 desc,
773 state_revision,
774 logging: Arc::new(QCell::new(&self.qcell_owner, logging)),
775 };
776 self.prepared_statements.insert(name, statement);
777 }
778
779 pub fn remove_prepared_statement(&mut self, name: &str) -> bool {
783 let removed = self.prepared_statements.remove(name).is_some();
784 if removed {
785 self.state_revision += 1;
786 }
787 removed
788 }
789
790 pub fn remove_all_prepared_statements(&mut self) {
792 self.state_revision += 1;
793 self.prepared_statements.clear();
794 }
795
796 pub fn get_prepared_statement_unverified(&self, name: &str) -> Option<&PreparedStatement> {
801 self.prepared_statements.get(name)
802 }
803
804 pub fn get_prepared_statement_mut_unverified(
809 &mut self,
810 name: &str,
811 ) -> Option<&mut PreparedStatement> {
812 self.prepared_statements.get_mut(name)
813 }
814
815 pub fn prepared_statements(&self) -> &BTreeMap<String, PreparedStatement> {
817 &self.prepared_statements
818 }
819
820 pub fn portals(&self) -> &BTreeMap<String, Portal> {
822 &self.portals
823 }
824
825 pub fn set_portal(
835 &mut self,
836 portal_name: String,
837 desc: StatementDesc,
838 stmt: Option<Statement<Raw>>,
839 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
840 params: Vec<(Datum, SqlScalarType)>,
841 result_formats: Vec<Format>,
842 state_revision: StateRevision,
843 ) -> Result<(), AdapterError> {
844 if !portal_name.is_empty() && self.portals.contains_key(&portal_name) {
846 return Err(AdapterError::DuplicateCursor(portal_name));
847 }
848 let state_revision = self.advance_state_revision_for_insert(state_revision);
849 let param_types = desc.param_types.clone();
850 self.portals.insert(
851 portal_name,
852 Portal {
853 stmt: stmt.map(Arc::new),
854 desc,
855 state_revision,
856 parameters: Params {
857 datums: Row::pack(params.iter().map(|(d, _t)| d)),
858 execute_types: params.into_iter().map(|(_d, t)| t).collect(),
859 expected_types: param_types,
860 },
861 result_formats,
862 state: PortalState::NotStarted,
863 logging,
864 lifecycle_timestamps: None,
865 },
866 );
867 Ok(())
868 }
869
870 pub fn remove_portal(&mut self, portal_name: &str) -> bool {
874 self.state_revision += 1;
875 self.portals.remove(portal_name).is_some()
876 }
877
878 pub fn get_portal_unverified(&self, portal_name: &str) -> Option<&Portal> {
882 self.portals.get(portal_name)
883 }
884
885 pub fn get_portal_unverified_mut(&mut self, portal_name: &str) -> Option<PortalRefMut<'_>> {
892 self.portals.get_mut(portal_name).map(|p| PortalRefMut {
893 stmt: &p.stmt,
894 desc: &p.desc,
895 state_revision: &mut p.state_revision,
896 parameters: &mut p.parameters,
897 result_formats: &mut p.result_formats,
898 logging: &mut p.logging,
899 state: &mut p.state,
900 lifecycle_timestamps: &mut p.lifecycle_timestamps,
901 })
902 }
903
904 pub fn create_new_portal(
906 &mut self,
907 stmt: Option<Statement<Raw>>,
908 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
909 desc: StatementDesc,
910 parameters: Params,
911 result_formats: Vec<Format>,
912 state_revision: StateRevision,
913 ) -> Result<String, AdapterError> {
914 let state_revision = self.advance_state_revision_for_insert(state_revision);
915
916 for i in self.portals.len().. {
918 let name = format!("<unnamed portal {}>", i);
919 match self.portals.entry(name.clone()) {
920 Entry::Occupied(_) => continue,
921 Entry::Vacant(entry) => {
922 entry.insert(Portal {
923 stmt: stmt.map(Arc::new),
924 desc,
925 state_revision,
926 parameters,
927 result_formats,
928 state: PortalState::NotStarted,
929 logging,
930 lifecycle_timestamps: None,
931 });
932 return Ok(name);
933 }
934 }
935 }
936
937 coord_bail!("unable to create a new portal");
938 }
939
940 pub fn reset(&mut self) -> BTreeMap<&'static str, String> {
944 let _ = self.clear_transaction();
945 self.remove_all_prepared_statements();
946 self.vars.reset_all()
947 }
948
949 pub fn application_name(&self) -> &str {
953 self.vars.application_name()
954 }
955
956 pub fn vars(&self) -> &SessionVars {
958 &self.vars
959 }
960
961 pub fn vars_mut(&mut self) -> &mut SessionVars {
963 &mut self.vars
964 }
965
966 pub fn apply_external_metadata_updates(&mut self) {
968 let Some(rx) = &mut self.external_metadata_rx else {
970 return;
971 };
972
973 if !rx.has_changed().unwrap_or(false) {
975 return;
976 }
977
978 let metadata = rx.borrow_and_update().clone();
981 self.vars.set_external_user_metadata(metadata);
982 }
983
984 pub fn apply_internal_user_metadata(&mut self, metadata: InternalUserMetadata) {
986 self.vars.set_internal_user_metadata(metadata);
987 }
988
989 pub fn initialize_role_metadata(&mut self, role_id: RoleId) {
991 self.role_metadata = Some(RoleMetadata::new(role_id));
992 }
993
994 pub fn ensure_timestamp_oracle(&mut self, timeline: Timeline) -> &mut InMemoryTimestampOracle {
997 self.session_oracles.entry(timeline).or_insert_with(|| {
998 InMemoryTimestampOracle::new(Timestamp::minimum(), NowFn::from(Timestamp::minimum))
999 })
1000 }
1001
1002 pub fn ensure_local_timestamp_oracle(&mut self) -> &mut InMemoryTimestampOracle {
1005 self.ensure_timestamp_oracle(Timeline::EpochMilliseconds)
1006 }
1007
1008 pub fn get_timestamp_oracle(&self, timeline: &Timeline) -> Option<&InMemoryTimestampOracle> {
1010 self.session_oracles.get(timeline)
1011 }
1012
1013 pub fn apply_write(&mut self, timestamp: Timestamp) {
1016 if self.vars().transaction_isolation() == &IsolationLevel::StrongSessionSerializable {
1017 self.ensure_local_timestamp_oracle().apply_write(timestamp);
1018 }
1019 }
1020
1021 pub fn metrics(&self) -> &SessionMetrics {
1023 &self.metrics
1024 }
1025
1026 pub fn set_builtin_table_updates(&mut self, fut: BuiltinTableAppendNotify) {
1028 let prev = self.builtin_updates.replace(fut);
1029 mz_ore::soft_assert_or_log!(prev.is_none(), "replacing old builtin table notify");
1030 }
1031
1032 pub fn clear_builtin_table_updates(&mut self) -> Option<impl Future<Output = ()> + 'static> {
1035 if let Some(fut) = self.builtin_updates.take() {
1036 let histogram = self
1038 .metrics()
1039 .session_startup_table_writes_seconds()
1040 .clone();
1041 Some(async move {
1042 fut.wall_time().observe(histogram).await;
1043 })
1044 } else {
1045 None
1046 }
1047 }
1048
1049 pub fn state_revision(&self) -> u64 {
1052 self.state_revision
1053 }
1054
1055 pub(crate) fn advance_state_revision(&mut self) {
1057 self.state_revision += 1;
1058 }
1059
1060 fn advance_state_revision_for_insert(&mut self, mut verified: StateRevision) -> StateRevision {
1063 let was_current = verified.session_state_revision == self.state_revision;
1064 self.state_revision += 1;
1065 if was_current {
1067 verified.session_state_revision = self.state_revision;
1068 }
1069 verified
1070 }
1071}
1072
1073#[derive(Derivative, Clone)]
1075#[derivative(Debug)]
1076pub struct PreparedStatement {
1077 stmt: Option<Statement<Raw>>,
1078 desc: StatementDesc,
1079 pub state_revision: StateRevision,
1081 #[derivative(Debug = "ignore")]
1082 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
1083}
1084
1085impl PreparedStatement {
1086 pub fn stmt(&self) -> Option<&Statement<Raw>> {
1089 self.stmt.as_ref()
1090 }
1091
1092 pub fn desc(&self) -> &StatementDesc {
1094 &self.desc
1095 }
1096
1097 pub fn logging(&self) -> &Arc<QCell<PreparedStatementLoggingInfo>> {
1099 &self.logging
1100 }
1101}
1102
1103#[derive(Derivative)]
1105#[derivative(Debug)]
1106pub struct Portal {
1107 pub stmt: Option<Arc<Statement<Raw>>>,
1109 pub desc: StatementDesc,
1111 pub state_revision: StateRevision,
1113 pub parameters: Params,
1115 pub result_formats: Vec<Format>,
1117 #[derivative(Debug = "ignore")]
1119 pub logging: Arc<QCell<PreparedStatementLoggingInfo>>,
1120 #[derivative(Debug = "ignore")]
1122 pub state: PortalState,
1123 pub lifecycle_timestamps: Option<LifecycleTimestamps>,
1125}
1126
1127pub struct PortalRefMut<'a> {
1132 pub stmt: &'a Option<Arc<Statement<Raw>>>,
1134 pub desc: &'a StatementDesc,
1136 pub state_revision: &'a mut StateRevision,
1138 pub parameters: &'a mut Params,
1140 pub result_formats: &'a mut Vec<Format>,
1142 pub logging: &'a mut Arc<QCell<PreparedStatementLoggingInfo>>,
1144 pub state: &'a mut PortalState,
1146 pub lifecycle_timestamps: &'a mut Option<LifecycleTimestamps>,
1148}
1149
1150#[derive(Debug, Clone, Copy, PartialEq)]
1154pub struct StateRevision {
1155 pub catalog_revision: u64,
1157 pub session_state_revision: u64,
1159}
1160
1161pub enum PortalState {
1163 NotStarted,
1165 InProgress(Option<InProgressRows>),
1168 Completed(Option<String>),
1172}
1173
1174pub struct InProgressRows {
1176 pub current: Option<Box<dyn RowIterator + Send + Sync>>,
1178 pub remaining: RecordFirstRowStream,
1180}
1181
1182impl InProgressRows {
1183 pub fn new(remaining: RecordFirstRowStream) -> Self {
1185 Self {
1186 current: None,
1187 remaining,
1188 }
1189 }
1190
1191 pub fn no_more_rows(&self) -> bool {
1194 self.remaining.no_more_rows && self.current.is_none()
1195 }
1196}
1197
1198pub type RowBatchStream = Box<dyn futures::Stream<Item = PeekResponseUnary> + Unpin + Send + Sync>;
1206
1207#[derive(Debug, Clone)]
1210pub struct LifecycleTimestamps {
1211 pub received: EpochMillis,
1216}
1217
1218impl LifecycleTimestamps {
1219 pub fn new(received: EpochMillis) -> Self {
1221 Self { received }
1222 }
1223}
1224
1225#[derive(Debug)]
1229pub enum TransactionStatus {
1230 Default,
1232 Started(Transaction),
1240 InTransaction(Transaction),
1242 InTransactionImplicit(Transaction),
1245 Failed(Transaction),
1247}
1248
1249impl TransactionStatus {
1250 pub fn into_ops(self) -> Option<TransactionOps> {
1252 match self {
1253 TransactionStatus::Default | TransactionStatus::Failed(_) => None,
1254 TransactionStatus::Started(txn)
1255 | TransactionStatus::InTransaction(txn)
1256 | TransactionStatus::InTransactionImplicit(txn) => Some(txn.ops),
1257 }
1258 }
1259
1260 pub fn inner(&self) -> Option<&Transaction> {
1262 match self {
1263 TransactionStatus::Default => None,
1264 TransactionStatus::Started(txn)
1265 | TransactionStatus::InTransaction(txn)
1266 | TransactionStatus::InTransactionImplicit(txn)
1267 | TransactionStatus::Failed(txn) => Some(txn),
1268 }
1269 }
1270
1271 pub fn inner_mut(&mut self) -> Option<&mut Transaction> {
1273 match self {
1274 TransactionStatus::Default => None,
1275 TransactionStatus::Started(txn)
1276 | TransactionStatus::InTransaction(txn)
1277 | TransactionStatus::InTransactionImplicit(txn)
1278 | TransactionStatus::Failed(txn) => Some(txn),
1279 }
1280 }
1281
1282 fn can_retain_ddl_inspections(&self) -> bool {
1288 match self {
1289 Self::Started(txn) | Self::InTransaction(txn) | Self::InTransactionImplicit(txn) => {
1290 !txn.contains_explain
1291 && match txn.ops {
1292 TransactionOps::None | TransactionOps::DDL { .. } => true,
1293 TransactionOps::Peeks { .. }
1294 | TransactionOps::Writes(_)
1295 | TransactionOps::Subscribe
1296 | TransactionOps::SingleStatement { .. } => false,
1297 }
1298 }
1299 Self::Default | Self::Failed(_) => false,
1300 }
1301 }
1302
1303 pub(crate) fn record_explain(&mut self) -> Result<(), AdapterError> {
1305 let txn = self.inner_mut().expect("active transaction");
1306 if matches!(txn.ops, TransactionOps::DDL { .. }) {
1307 return Err(AdapterError::DDLOnlyTransaction);
1308 }
1309 txn.contains_explain = true;
1312 txn.pending_ddl_inspections.clear();
1313 Ok(())
1314 }
1315
1316 pub fn is_ddl(&self) -> bool {
1318 match self {
1319 TransactionStatus::Default => false,
1320 TransactionStatus::Started(txn)
1321 | TransactionStatus::InTransaction(txn)
1322 | TransactionStatus::InTransactionImplicit(txn)
1323 | TransactionStatus::Failed(txn) => {
1324 matches!(txn.ops, TransactionOps::DDL { .. })
1325 }
1326 }
1327 }
1328
1329 pub fn is_implicit(&self) -> bool {
1332 match self {
1333 TransactionStatus::Started(_) | TransactionStatus::InTransactionImplicit(_) => true,
1334 TransactionStatus::Default
1335 | TransactionStatus::InTransaction(_)
1336 | TransactionStatus::Failed(_) => false,
1337 }
1338 }
1339
1340 pub fn may_span_pipeline(&self) -> bool {
1348 match self {
1349 TransactionStatus::Started(txn) => match &txn.ops {
1350 TransactionOps::Writes(_) => true,
1351 TransactionOps::None
1352 | TransactionOps::Peeks { .. }
1353 | TransactionOps::Subscribe
1354 | TransactionOps::SingleStatement { .. }
1355 | TransactionOps::DDL { .. } => false,
1356 },
1357 TransactionStatus::Default
1358 | TransactionStatus::InTransaction(_)
1359 | TransactionStatus::InTransactionImplicit(_)
1360 | TransactionStatus::Failed(_) => false,
1361 }
1362 }
1363
1364 pub fn is_in_multi_statement_transaction(&self) -> bool {
1366 match self {
1367 TransactionStatus::InTransaction(_) | TransactionStatus::InTransactionImplicit(_) => {
1368 true
1369 }
1370 TransactionStatus::Default
1371 | TransactionStatus::Started(_)
1372 | TransactionStatus::Failed(_) => false,
1373 }
1374 }
1375
1376 pub fn may_share_transaction_with_other_statements(&self) -> bool {
1396 self.is_in_multi_statement_transaction() || self.contains_ops()
1397 }
1398
1399 pub fn in_immediate_multi_stmt_txn(&self, when: &QueryWhen) -> bool {
1401 self.is_in_multi_statement_transaction() && when == &QueryWhen::Immediately
1402 }
1403
1404 pub fn timeline(&self) -> Option<Timeline> {
1406 match self {
1407 TransactionStatus::Default => None,
1408 TransactionStatus::Started(txn)
1409 | TransactionStatus::InTransaction(txn)
1410 | TransactionStatus::InTransactionImplicit(txn)
1411 | TransactionStatus::Failed(txn) => txn.timeline(),
1412 }
1413 }
1414
1415 pub fn cluster(&self) -> Option<ClusterId> {
1417 match self {
1418 TransactionStatus::Default => None,
1419 TransactionStatus::Started(txn)
1420 | TransactionStatus::InTransaction(txn)
1421 | TransactionStatus::InTransactionImplicit(txn)
1422 | TransactionStatus::Failed(txn) => txn.cluster(),
1423 }
1424 }
1425
1426 pub fn catalog_state(&self) -> Option<&CatalogState> {
1428 match self.inner() {
1429 Some(Transaction {
1430 ops: TransactionOps::DDL { state, .. },
1431 ..
1432 }) => Some(state),
1433 _ => None,
1434 }
1435 }
1436
1437 pub fn contains_ops(&self) -> bool {
1439 match self.inner() {
1440 Some(txn) => txn.contains_ops(),
1441 None => false,
1442 }
1443 }
1444
1445 pub fn allows_writes(&self) -> bool {
1448 match self {
1449 TransactionStatus::Started(Transaction { ops, access, .. })
1450 | TransactionStatus::InTransaction(Transaction { ops, access, .. })
1451 | TransactionStatus::InTransactionImplicit(Transaction { ops, access, .. }) => {
1452 match ops {
1453 TransactionOps::None => access != &Some(TransactionAccessMode::ReadOnly),
1454 TransactionOps::Peeks { determination, .. } => {
1455 access != &Some(TransactionAccessMode::ReadOnly)
1460 && !determination.timestamp_context.contains_timestamp()
1461 }
1462 TransactionOps::Subscribe => false,
1463 TransactionOps::Writes(_) => true,
1464 TransactionOps::SingleStatement { .. } => false,
1465 TransactionOps::DDL { .. } => false,
1466 }
1467 }
1468 TransactionStatus::Default | TransactionStatus::Failed(_) => {
1469 unreachable!()
1470 }
1471 }
1472 }
1473
1474 pub fn add_ops(&mut self, mut add_ops: TransactionOps) -> Result<(), AdapterError> {
1487 if matches!(add_ops, TransactionOps::DDL { .. })
1488 && self.inner().is_some_and(|txn| txn.contains_explain)
1489 {
1490 return Err(AdapterError::DDLOnlyTransaction);
1491 }
1492 match self {
1493 TransactionStatus::Started(Transaction {
1494 ops,
1495 access,
1496 pending_ddl_inspections,
1497 ..
1498 })
1499 | TransactionStatus::InTransaction(Transaction {
1500 ops,
1501 access,
1502 pending_ddl_inspections,
1503 ..
1504 })
1505 | TransactionStatus::InTransactionImplicit(Transaction {
1506 ops,
1507 access,
1508 pending_ddl_inspections,
1509 ..
1510 }) => {
1511 match ops {
1512 TransactionOps::None => {
1513 if matches!(access, Some(TransactionAccessMode::ReadOnly))
1514 && matches!(add_ops, TransactionOps::Writes(_))
1515 {
1516 return Err(AdapterError::ReadOnlyTransaction);
1517 }
1518 match &mut add_ops {
1519 TransactionOps::DDL { commands, .. } => {
1520 commands.splice(
1523 0..0,
1524 pending_ddl_inspections
1525 .drain(..)
1526 .map(DdlInspection::into_command),
1527 );
1528 }
1529 TransactionOps::None => {}
1530 TransactionOps::Peeks { .. }
1531 | TransactionOps::Writes(_)
1532 | TransactionOps::Subscribe
1533 | TransactionOps::SingleStatement { .. } => {
1534 pending_ddl_inspections.clear();
1535 }
1536 }
1537 *ops = add_ops;
1538 }
1539 TransactionOps::Peeks {
1540 determination,
1541 cluster_id,
1542 requires_linearization,
1543 } => match add_ops {
1544 TransactionOps::Peeks {
1545 determination: add_timestamp_determination,
1546 cluster_id: add_cluster_id,
1547 requires_linearization: add_requires_linearization,
1548 } => {
1549 assert_eq!(*cluster_id, add_cluster_id);
1550 match (
1551 &determination.timestamp_context,
1552 &add_timestamp_determination.timestamp_context,
1553 ) {
1554 (
1555 TimestampContext::TimelineTimestamp {
1556 timeline: txn_timeline,
1557 chosen_ts: txn_ts,
1558 oracle_ts: _,
1559 },
1560 TimestampContext::TimelineTimestamp {
1561 timeline: add_timeline,
1562 chosen_ts: add_ts,
1563 oracle_ts: _,
1564 },
1565 ) => {
1566 assert_eq!(txn_timeline, add_timeline);
1567 assert_eq!(txn_ts, add_ts);
1568 }
1569 (TimestampContext::NoTimestamp, _) => {
1570 *determination = add_timestamp_determination
1571 }
1572 (_, TimestampContext::NoTimestamp) => {}
1573 };
1574 if matches!(requires_linearization, RequireLinearization::NotRequired)
1575 && matches!(
1576 add_requires_linearization,
1577 RequireLinearization::Required
1578 )
1579 {
1580 *requires_linearization = add_requires_linearization;
1581 }
1582 }
1583 writes @ TransactionOps::Writes(..)
1592 if !determination.timestamp_context.contains_timestamp() =>
1593 {
1594 if matches!(access, Some(TransactionAccessMode::ReadOnly)) {
1595 return Err(AdapterError::ReadOnlyTransaction);
1596 }
1597 *ops = writes;
1598 }
1599 _ => return Err(AdapterError::ReadOnlyTransaction),
1600 },
1601 TransactionOps::Subscribe => {
1602 return Err(AdapterError::SubscribeOnlyTransaction);
1603 }
1604 TransactionOps::Writes(txn_writes) => match add_ops {
1605 TransactionOps::Writes(mut add_writes) => {
1606 assert!(!matches!(access, Some(TransactionAccessMode::ReadOnly)));
1609 txn_writes.append(&mut add_writes);
1610 }
1611 TransactionOps::Peeks { determination, .. }
1614 if !determination.timestamp_context.contains_timestamp() => {}
1615 _ => {
1616 return Err(AdapterError::WriteOnlyTransaction);
1617 }
1618 },
1619 TransactionOps::SingleStatement { .. } => {
1620 return Err(AdapterError::SingleStatementTransaction);
1621 }
1622 TransactionOps::DDL {
1623 commands,
1624 state,
1625 snapshot,
1626 } => match add_ops {
1627 TransactionOps::DDL {
1628 commands: new_commands,
1629 state: new_state,
1630 snapshot: new_snapshot,
1631 } => {
1632 if !new_commands.is_empty() {
1633 commands.extend(new_commands);
1634 *state = new_state;
1635 *snapshot = new_snapshot;
1636 }
1637 }
1638 _ => return Err(AdapterError::DDLOnlyTransaction),
1639 },
1640 }
1641 }
1642 TransactionStatus::Default | TransactionStatus::Failed(_) => {
1643 unreachable!()
1644 }
1645 }
1646 Ok(())
1647 }
1648}
1649
1650pub type TransactionId = u64;
1652
1653impl Default for TransactionStatus {
1654 fn default() -> Self {
1655 TransactionStatus::Default
1656 }
1657}
1658
1659#[derive(Debug)]
1666enum DdlInspection {
1667 CatalogResult(Arc<crate::catalog::command::CatalogResultCommand>),
1668 Description(Arc<crate::catalog::command::DescriptionCommand>),
1669}
1670
1671impl DdlInspection {
1672 fn into_command(self) -> crate::catalog::command::CatalogCommand {
1673 match self {
1674 Self::CatalogResult(command) => {
1675 crate::catalog::command::CatalogCommand::CatalogResult(command)
1676 }
1677 Self::Description(command) => {
1678 crate::catalog::command::CatalogCommand::Description(command)
1679 }
1680 }
1681 }
1682}
1683
1684#[derive(Debug)]
1686pub struct Transaction {
1687 completion_owner: TransactionCompletionOwner,
1688 pub pcx: PlanContext,
1690 pub ops: TransactionOps,
1692 pending_ddl_inspections: Vec<DdlInspection>,
1694 contains_explain: bool,
1695 pub id: TransactionId,
1700 access: Option<TransactionAccessMode>,
1702}
1703
1704#[derive(Debug, PartialEq)]
1705enum TransactionCompletionOwner {
1706 Session,
1707 Coordinator,
1708}
1709
1710pub(crate) struct ReadOnlyCompletion {
1712 pub action: EndTransactionAction,
1713 pub timestamp: Option<TimestampContext>,
1714}
1715
1716impl Transaction {
1717 fn timeline(&self) -> Option<Timeline> {
1719 match &self.ops {
1720 TransactionOps::Peeks {
1721 determination:
1722 TimestampDetermination {
1723 timestamp_context: TimestampContext::TimelineTimestamp { timeline, .. },
1724 ..
1725 },
1726 ..
1727 } => Some(timeline.clone()),
1728 TransactionOps::Peeks { .. }
1729 | TransactionOps::None
1730 | TransactionOps::Subscribe
1731 | TransactionOps::Writes(_)
1732 | TransactionOps::SingleStatement { .. }
1733 | TransactionOps::DDL { .. } => None,
1734 }
1735 }
1736
1737 pub fn cluster(&self) -> Option<ClusterId> {
1739 match &self.ops {
1740 TransactionOps::Peeks { cluster_id, .. } => Some(cluster_id.clone()),
1741 TransactionOps::None
1742 | TransactionOps::Subscribe
1743 | TransactionOps::Writes(_)
1744 | TransactionOps::SingleStatement { .. }
1745 | TransactionOps::DDL { .. } => None,
1746 }
1747 }
1748
1749 fn contains_ops(&self) -> bool {
1751 !matches!(self.ops, TransactionOps::None)
1752 }
1753}
1754
1755#[derive(Debug, Clone, Copy)]
1757pub enum TransactionCode {
1758 Idle,
1760 InTransaction,
1762 Failed,
1764}
1765
1766impl From<TransactionCode> for u8 {
1767 fn from(code: TransactionCode) -> Self {
1768 match code {
1769 TransactionCode::Idle => b'I',
1770 TransactionCode::InTransaction => b'T',
1771 TransactionCode::Failed => b'E',
1772 }
1773 }
1774}
1775
1776impl From<TransactionCode> for String {
1777 fn from(code: TransactionCode) -> Self {
1778 char::from(u8::from(code)).to_string()
1779 }
1780}
1781
1782impl From<&TransactionStatus> for TransactionCode {
1783 fn from(status: &TransactionStatus) -> TransactionCode {
1785 match status {
1786 TransactionStatus::Default => TransactionCode::Idle,
1787 TransactionStatus::Started(_) => TransactionCode::InTransaction,
1788 TransactionStatus::InTransaction(_) => TransactionCode::InTransaction,
1789 TransactionStatus::InTransactionImplicit(_) => TransactionCode::InTransaction,
1790 TransactionStatus::Failed(_) => TransactionCode::Failed,
1791 }
1792 }
1793}
1794
1795#[derive(Derivative)]
1801#[derivative(Debug)]
1802pub enum TransactionOps {
1803 None,
1806 Peeks {
1811 determination: TimestampDetermination,
1813 cluster_id: ClusterId,
1815 requires_linearization: RequireLinearization,
1817 },
1818 Subscribe,
1820 Writes(Vec<WriteOp>),
1823 SingleStatement {
1825 stmt: Arc<Statement<Raw>>,
1827 params: mz_sql::plan::Params,
1829 },
1830 DDL {
1834 commands: Vec<crate::catalog::command::CatalogCommand>,
1836 state: CatalogState,
1838 snapshot: Snapshot,
1840 },
1841}
1842
1843impl TransactionOps {
1844 pub fn stages_work(&self) -> bool {
1848 matches!(
1849 self,
1850 TransactionOps::Writes(_)
1851 | TransactionOps::DDL { .. }
1852 | TransactionOps::SingleStatement { .. }
1853 )
1854 }
1855}
1856
1857impl Default for TransactionOps {
1858 fn default() -> Self {
1859 Self::None
1860 }
1861}
1862
1863#[derive(Debug, Clone, PartialEq)]
1865pub struct WriteOp {
1866 pub id: CatalogItemId,
1868 pub rows: TableData,
1870}
1871
1872#[derive(Debug)]
1874pub enum RequireLinearization {
1875 Required,
1877 NotRequired,
1879}
1880
1881impl From<&ExplainContext> for RequireLinearization {
1882 fn from(ctx: &ExplainContext) -> Self {
1883 match ctx {
1884 ExplainContext::None | ExplainContext::PlanInsightsNotice(_) => {
1885 RequireLinearization::Required
1886 }
1887 ExplainContext::Plan(_) | ExplainContext::Pushdown | ExplainContext::Timestamp => {
1888 RequireLinearization::NotRequired
1889 }
1890 }
1891 }
1892}
1893#[cfg(test)]
1894mod tests {
1895 use super::*;
1896 use mz_sql::session::vars::{SystemVars, VarInput};
1897 use timely::progress::Antichain;
1898
1899 fn read_session() -> Session {
1900 let mut session = Session::dummy();
1901 session.start_transaction_single_stmt(Utc::now());
1902 session
1903 .add_transaction_ops(TransactionOps::Peeks {
1904 determination: TimestampDetermination {
1905 timestamp_context: TimestampContext::TimelineTimestamp {
1906 timeline: Timeline::EpochMilliseconds,
1907 chosen_ts: 10.into(),
1908 oracle_ts: Some(10.into()),
1909 },
1910 since: Antichain::from_elem(0.into()),
1911 upper: Antichain::new(),
1912 largest_not_in_advance_of_upper: Timestamp::MAX,
1913 oracle_read_ts: Some(10.into()),
1914 session_oracle_read_ts: None,
1915 real_time_recency_ts: None,
1916 constraints: Default::default(),
1917 },
1918 cluster_id: ClusterId::User(1),
1919 requires_linearization: RequireLinearization::Required,
1920 })
1921 .expect("read transaction");
1922 session
1923 }
1924
1925 #[mz_ore::test]
1926 fn read_completion_tracks_ownership_not_just_ops() {
1927 let mut session = read_session();
1928 let completion = session
1929 .read_only_completion(EndTransactionAction::Commit)
1930 .expect("local read");
1931 assert_eq!(completion.action, EndTransactionAction::Commit);
1932 assert!(completion.timestamp.is_some());
1933 session.require_coordinator_completion();
1934 assert!(
1935 session
1936 .read_only_completion(EndTransactionAction::Commit)
1937 .is_none()
1938 );
1939 let _ = session.clear_transaction();
1940 session.start_transaction_single_stmt(Utc::now());
1941 assert!(
1942 session
1943 .read_only_completion(EndTransactionAction::Commit)
1944 .is_some()
1945 );
1946 }
1947
1948 #[mz_ore::test]
1949 fn completion_skips_timestamp_for_failed_and_rolled_back_reads() {
1950 let session = read_session();
1951 let rollback = session
1952 .read_only_completion(EndTransactionAction::Rollback)
1953 .expect("local read");
1954 assert!(rollback.timestamp.is_none());
1955 let session = session.fail_transaction();
1956 let failed = session
1957 .read_only_completion(EndTransactionAction::Commit)
1958 .expect("failed local read");
1959 assert_eq!(failed.action, EndTransactionAction::Rollback);
1960 assert!(failed.timestamp.is_none());
1961 }
1962
1963 #[mz_ore::test]
1964 fn completion_rejects_resource_bearing_transactions() {
1965 for ops in [
1966 TransactionOps::Subscribe,
1967 TransactionOps::Writes(Vec::new()),
1968 ] {
1969 let mut session = Session::dummy();
1970 session.start_transaction_single_stmt(Utc::now());
1971 session.add_transaction_ops(ops).expect("first operation");
1972 assert!(
1973 session
1974 .read_only_completion(EndTransactionAction::Commit)
1975 .is_none()
1976 );
1977 assert!(
1978 session
1979 .fail_transaction()
1980 .read_only_completion(EndTransactionAction::Rollback)
1981 .is_none()
1982 );
1983 }
1984 }
1985
1986 #[mz_ore::test]
1987 fn read_completion_preserves_transactional_parameter_changes() {
1988 for action in [EndTransactionAction::Commit, EndTransactionAction::Rollback] {
1989 let mut session = read_session();
1990 session
1991 .vars_mut()
1992 .set_default("application_name", VarInput::Flat("session"))
1993 .expect("default");
1994 session
1995 .vars_mut()
1996 .set(
1997 &SystemVars::new(),
1998 "application_name",
1999 VarInput::Flat("local"),
2000 true,
2001 )
2002 .expect("local setting");
2003 let completion = session.read_only_completion(action).expect("local read");
2004 let _ = session.clear_transaction();
2005 let params = session.vars_mut().end_transaction(completion.action);
2006 assert_eq!(
2007 params.get("application_name").map(String::as_str),
2008 Some("session")
2009 );
2010 assert_eq!(session.vars().application_name(), "session");
2011 assert!(matches!(session.transaction(), TransactionStatus::Default));
2012 }
2013 }
2014
2015 #[mz_ore::test]
2016 fn ddl_inspections_are_released_when_ddl_becomes_impossible() {
2017 use mz_sql::plan::{Params, StatementDesc};
2018 use timely::progress::Antichain;
2019
2020 let statement = mz_sql_parser::parser::parse_statements("SELECT 1")
2021 .expect("valid SQL")
2022 .remove(0)
2023 .ast;
2024 let modes = [
2025 TransactionOps::Peeks {
2026 determination: TimestampDetermination {
2027 timestamp_context: TimestampContext::NoTimestamp,
2028 since: Antichain::new(),
2029 upper: Antichain::new(),
2030 largest_not_in_advance_of_upper: mz_repr::Timestamp::MIN,
2031 oracle_read_ts: None,
2032 session_oracle_read_ts: None,
2033 real_time_recency_ts: None,
2034 constraints: Default::default(),
2035 },
2036 cluster_id: mz_controller_types::ClusterId::User(1),
2037 requires_linearization: RequireLinearization::NotRequired,
2038 },
2039 TransactionOps::Writes(vec![]),
2040 TransactionOps::Subscribe,
2041 TransactionOps::SingleStatement {
2042 stmt: Arc::new(statement.clone()),
2043 params: Params::empty(),
2044 },
2045 ];
2046 for mode in modes.into_iter().map(Some).chain([None]) {
2048 let mut session = Session::dummy();
2049 session.start_transaction_implicit(Utc::now(), 2);
2050 let command = Arc::new(crate::catalog::command::DescriptionCommand::new(
2051 statement.clone(),
2052 vec![],
2053 session.meta(),
2054 StatementDesc::new(Some(mz_repr::RelationDesc::empty())),
2055 ));
2056 let retained = Arc::downgrade(&command);
2057 session.retain_ddl_inspection(DdlInspection::Description(command));
2058 assert!(retained.upgrade().is_some(), "DDL is still possible");
2059 if let Some(mode) = mode {
2060 session.add_transaction_ops(mode).expect("valid transition");
2061 } else {
2062 session
2063 .transaction_mut()
2064 .record_explain()
2065 .expect("EXPLAIN allowed");
2066 }
2067 assert!(retained.upgrade().is_none(), "release earlier inspections");
2068 let command = Arc::new(crate::catalog::command::DescriptionCommand::new(
2069 statement.clone(),
2070 vec![],
2071 session.meta(),
2072 StatementDesc::new(Some(mz_repr::RelationDesc::empty())),
2073 ));
2074 let discarded = Arc::downgrade(&command);
2075 session.retain_ddl_inspection(DdlInspection::Description(command));
2076 assert!(
2077 discarded.upgrade().is_none(),
2078 "do not retain later inspections"
2079 );
2080 }
2081 }
2082}