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) {
439 if let TransactionStatus::Default = self.transaction {
440 let id = self.next_transaction_id;
441 self.next_transaction_id = self.next_transaction_id.wrapping_add(1);
442 let txn = Transaction {
443 completion_owner: TransactionCompletionOwner::Session,
444 pcx: self.new_pcx(wall_time),
445 ops: TransactionOps::None,
446 pending_ddl_inspections: Vec::new(),
447 contains_explain: false,
448 access: None,
449 id,
450 };
451 match stmts {
452 1 => self.transaction = TransactionStatus::Started(txn),
453 n if n > 1 => self.transaction = TransactionStatus::InTransactionImplicit(txn),
454 _ => {}
455 }
456 } else if stmts > 1 {
457 self.transaction = match std::mem::take(&mut self.transaction) {
461 TransactionStatus::Started(txn) => TransactionStatus::InTransactionImplicit(txn),
462 other => other,
463 };
464 }
465 }
466
467 pub fn start_transaction_single_stmt(&mut self, wall_time: DateTime<Utc>) {
469 self.start_transaction_implicit(wall_time, 1);
470 }
471
472 #[must_use]
482 pub fn clear_transaction(&mut self) -> TransactionStatus {
483 self.portals.clear();
484 self.pcx = None;
485 self.state_revision += 1;
486 mem::take(&mut self.transaction)
487 }
488
489 pub(crate) fn require_coordinator_completion(&mut self) {
492 if let Some(txn) = self.transaction.inner_mut() {
493 txn.completion_owner = TransactionCompletionOwner::Coordinator;
494 }
495 }
496
497 pub(crate) fn read_only_completion(
499 &self,
500 mut action: EndTransactionAction,
501 ) -> Option<ReadOnlyCompletion> {
502 let txn = self.transaction.inner()?;
503 if txn.completion_owner != TransactionCompletionOwner::Session {
504 return None;
505 }
506 let timestamp = match &txn.ops {
507 TransactionOps::None => None,
508 TransactionOps::Peeks {
509 determination,
510 requires_linearization,
511 ..
512 } => matches!(requires_linearization, RequireLinearization::Required)
513 .then(|| determination.timestamp_context.clone()),
514 TransactionOps::Writes(_)
515 | TransactionOps::Subscribe
516 | TransactionOps::SingleStatement { .. }
517 | TransactionOps::DDL { .. } => return None,
518 };
519 if matches!(self.transaction, TransactionStatus::Failed(_)) {
520 action = EndTransactionAction::Rollback;
521 }
522 Some(ReadOnlyCompletion {
523 action,
524 timestamp: if action == EndTransactionAction::Commit {
525 timestamp
526 } else {
527 None
528 },
529 })
530 }
531
532 pub fn fail_transaction(mut self) -> Self {
534 match self.transaction {
535 TransactionStatus::Default => unreachable!(),
536 TransactionStatus::Started(txn)
537 | TransactionStatus::InTransactionImplicit(txn)
538 | TransactionStatus::InTransaction(txn) => {
539 self.transaction = TransactionStatus::Failed(txn);
540 }
541 TransactionStatus::Failed(_) => {}
542 };
543 self
544 }
545
546 pub fn transaction(&self) -> &TransactionStatus {
548 &self.transaction
549 }
550
551 pub fn transaction_mut(&mut self) -> &mut TransactionStatus {
553 &mut self.transaction
554 }
555
556 pub fn transaction_code(&self) -> TransactionCode {
558 self.transaction().into()
559 }
560
561 pub(crate) fn retain_catalog_result(
563 &mut self,
564 command: Arc<crate::catalog::command::CatalogResultCommand>,
565 ) {
566 self.retain_ddl_inspection(DdlInspection::CatalogResult(command));
567 }
568
569 fn retain_ddl_inspection(&mut self, inspection: DdlInspection) {
570 if !self.transaction().can_retain_ddl_inspections() {
571 return;
572 }
573 let txn = self
574 .transaction_mut()
575 .inner_mut()
576 .expect("active transaction");
577 match &mut txn.ops {
578 TransactionOps::DDL { commands, .. } => commands.push(inspection.into_command()),
579 _ => txn.pending_ddl_inspections.push(inspection),
580 }
581 }
582
583 pub(crate) fn retain_description(
585 &mut self,
586 statement: mz_sql::ast::Statement<mz_sql::ast::Raw>,
587 param_types: Vec<Option<mz_repr::SqlScalarType>>,
588 expected: mz_sql::plan::StatementDesc,
589 ) {
590 if !self.transaction().can_retain_ddl_inspections()
591 || (expected.relation_desc.is_none() && expected.param_types.is_empty())
592 {
593 return;
594 }
595 let mut described = &statement;
598 while let mz_sql::ast::Statement::Declare(declare) = described {
599 described = &declare.stmt;
600 }
601 if matches!(
602 described,
603 mz_sql::ast::Statement::Execute(_) | mz_sql::ast::Statement::Fetch(_)
604 ) {
605 return;
606 }
607 let command = crate::catalog::command::DescriptionCommand::new(
608 statement,
609 param_types,
610 self.meta(),
611 expected,
612 );
613 self.retain_ddl_inspection(DdlInspection::Description(Arc::new(command)));
614 }
615
616 pub fn add_transaction_ops(&mut self, add_ops: TransactionOps) -> Result<(), AdapterError> {
618 self.transaction.add_ops(add_ops)
619 }
620
621 pub fn retain_notice_transmitter(&self) -> UnboundedSender<AdapterNotice> {
623 self.notices_tx.clone()
624 }
625
626 pub fn add_notice(&self, notice: AdapterNotice) {
628 self.add_notices([notice])
629 }
630
631 pub fn add_notices(&self, notices: impl IntoIterator<Item = AdapterNotice>) {
633 for notice in notices {
634 let _ = self.notices_tx.send(notice);
635 }
636 }
637
638 pub async fn recv_notice(&mut self) -> AdapterNotice {
642 loop {
644 let notice = self
645 .notices_rx
646 .recv()
647 .await
648 .expect("Session also holds a sender, so recv won't ever return None");
649 match self.notice_filter(notice) {
650 Some(notice) => return notice,
651 None => continue,
652 }
653 }
654 }
655
656 pub fn drain_notices(&mut self) -> Vec<AdapterNotice> {
658 let mut notices = Vec::new();
659 while let Ok(notice) = self.notices_rx.try_recv() {
660 if let Some(notice) = self.notice_filter(notice) {
661 notices.push(notice);
662 }
663 }
664 notices
665 }
666
667 pub fn execution_time_notice(&self, time: ExecutionTime) -> Option<AdapterNotice> {
669 if !self.vars.emit_execution_time_notice() {
670 return None;
671 }
672 self.notice_filter(AdapterNotice::ExecutionTime(time))
673 }
674
675 pub fn maybe_mark_staged(&self, time: ExecutionTime) -> ExecutionTime {
681 let staged = self
682 .transaction()
683 .inner()
684 .is_some_and(|txn| txn.ops.stages_work());
685 if staged {
686 ExecutionTime {
687 kind: ExecutionTimeKind::Staged,
688 ..time
689 }
690 } else {
691 time
692 }
693 }
694
695 fn notice_filter(&self, notice: AdapterNotice) -> Option<AdapterNotice> {
697 let minimum_client_severity = self.vars.client_min_messages();
699 let sev = notice.severity();
700 if !minimum_client_severity.should_output_to_client(&sev) {
701 return None;
702 }
703 if let AdapterNotice::ClusterReplicaStatusChanged { cluster, .. } = ¬ice {
705 if cluster != self.vars.cluster() {
706 return None;
707 }
708 }
709 Some(notice)
710 }
711
712 pub fn clear_transaction_ops(&mut self) {
715 if let Some(txn) = self.transaction.inner_mut() {
716 txn.ops = TransactionOps::None;
717 }
718 }
719
720 pub fn get_transaction_timestamp_determination(&self) -> Option<TimestampDetermination> {
725 match self.transaction.inner() {
726 Some(Transaction {
727 pcx: _,
728 ops: TransactionOps::Peeks { determination, .. },
729 access: _,
730 id: _,
731 pending_ddl_inspections: _,
732 contains_explain: _,
733 completion_owner: _,
734 }) => Some(determination.clone()),
735 _ => None,
736 }
737 }
738
739 pub fn contains_read_timestamp(&self) -> bool {
741 matches!(
742 self.transaction.inner(),
743 Some(Transaction {
744 pcx: _,
745 ops: TransactionOps::Peeks {
746 determination: TimestampDetermination {
747 timestamp_context: TimestampContext::TimelineTimestamp { .. },
748 ..
749 },
750 ..
751 },
752 access: _,
753 id: _,
754 pending_ddl_inspections: _,
755 contains_explain: _,
756 completion_owner: _,
757 })
758 )
759 }
760
761 pub fn set_prepared_statement(
763 &mut self,
764 name: String,
765 stmt: Option<Statement<Raw>>,
766 raw_sql: String,
767 desc: StatementDesc,
768 state_revision: StateRevision,
769 now: EpochMillis,
770 ) {
771 let state_revision = self.advance_state_revision_for_insert(state_revision);
772 let logging = PreparedStatementLoggingInfo::still_to_log(
773 raw_sql,
774 stmt.as_ref(),
775 now,
776 name.clone(),
777 self.uuid,
778 false,
779 );
780 let statement = PreparedStatement {
781 stmt,
782 desc,
783 state_revision,
784 logging: Arc::new(QCell::new(&self.qcell_owner, logging)),
785 };
786 self.prepared_statements.insert(name, statement);
787 }
788
789 pub fn remove_prepared_statement(&mut self, name: &str) -> bool {
793 let removed = self.prepared_statements.remove(name).is_some();
794 if removed {
795 self.state_revision += 1;
796 }
797 removed
798 }
799
800 pub fn remove_all_prepared_statements(&mut self) {
802 self.state_revision += 1;
803 self.prepared_statements.clear();
804 }
805
806 pub fn get_prepared_statement_unverified(&self, name: &str) -> Option<&PreparedStatement> {
811 self.prepared_statements.get(name)
812 }
813
814 pub fn get_prepared_statement_mut_unverified(
819 &mut self,
820 name: &str,
821 ) -> Option<&mut PreparedStatement> {
822 self.prepared_statements.get_mut(name)
823 }
824
825 pub fn prepared_statements(&self) -> &BTreeMap<String, PreparedStatement> {
827 &self.prepared_statements
828 }
829
830 pub fn portals(&self) -> &BTreeMap<String, Portal> {
832 &self.portals
833 }
834
835 pub fn set_portal(
845 &mut self,
846 portal_name: String,
847 desc: StatementDesc,
848 stmt: Option<Statement<Raw>>,
849 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
850 params: Vec<(Datum, SqlScalarType)>,
851 result_formats: Vec<Format>,
852 state_revision: StateRevision,
853 ) -> Result<(), AdapterError> {
854 if !portal_name.is_empty() && self.portals.contains_key(&portal_name) {
856 return Err(AdapterError::DuplicateCursor(portal_name));
857 }
858 let state_revision = self.advance_state_revision_for_insert(state_revision);
859 let param_types = desc.param_types.clone();
860 self.portals.insert(
861 portal_name,
862 Portal {
863 stmt: stmt.map(Arc::new),
864 desc,
865 state_revision,
866 parameters: Params {
867 datums: Row::pack(params.iter().map(|(d, _t)| d)),
868 execute_types: params.into_iter().map(|(_d, t)| t).collect(),
869 expected_types: param_types,
870 },
871 result_formats,
872 state: PortalState::NotStarted,
873 logging,
874 lifecycle_timestamps: None,
875 },
876 );
877 Ok(())
878 }
879
880 pub fn remove_portal(&mut self, portal_name: &str) -> bool {
884 self.state_revision += 1;
885 self.portals.remove(portal_name).is_some()
886 }
887
888 pub fn get_portal_unverified(&self, portal_name: &str) -> Option<&Portal> {
892 self.portals.get(portal_name)
893 }
894
895 pub fn get_portal_unverified_mut(&mut self, portal_name: &str) -> Option<PortalRefMut<'_>> {
902 self.portals.get_mut(portal_name).map(|p| PortalRefMut {
903 stmt: &p.stmt,
904 desc: &p.desc,
905 state_revision: &mut p.state_revision,
906 parameters: &mut p.parameters,
907 result_formats: &mut p.result_formats,
908 logging: &mut p.logging,
909 state: &mut p.state,
910 lifecycle_timestamps: &mut p.lifecycle_timestamps,
911 })
912 }
913
914 pub fn create_new_portal(
916 &mut self,
917 stmt: Option<Statement<Raw>>,
918 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
919 desc: StatementDesc,
920 parameters: Params,
921 result_formats: Vec<Format>,
922 state_revision: StateRevision,
923 ) -> Result<String, AdapterError> {
924 let state_revision = self.advance_state_revision_for_insert(state_revision);
925
926 for i in self.portals.len().. {
928 let name = format!("<unnamed portal {}>", i);
929 match self.portals.entry(name.clone()) {
930 Entry::Occupied(_) => continue,
931 Entry::Vacant(entry) => {
932 entry.insert(Portal {
933 stmt: stmt.map(Arc::new),
934 desc,
935 state_revision,
936 parameters,
937 result_formats,
938 state: PortalState::NotStarted,
939 logging,
940 lifecycle_timestamps: None,
941 });
942 return Ok(name);
943 }
944 }
945 }
946
947 coord_bail!("unable to create a new portal");
948 }
949
950 pub fn reset(&mut self) -> BTreeMap<&'static str, String> {
954 let _ = self.clear_transaction();
955 self.remove_all_prepared_statements();
956 self.vars.reset_all()
957 }
958
959 pub fn application_name(&self) -> &str {
963 self.vars.application_name()
964 }
965
966 pub fn vars(&self) -> &SessionVars {
968 &self.vars
969 }
970
971 pub fn vars_mut(&mut self) -> &mut SessionVars {
973 &mut self.vars
974 }
975
976 pub fn apply_external_metadata_updates(&mut self) {
978 let Some(rx) = &mut self.external_metadata_rx else {
980 return;
981 };
982
983 if !rx.has_changed().unwrap_or(false) {
985 return;
986 }
987
988 let metadata = rx.borrow_and_update().clone();
991 self.vars.set_external_user_metadata(metadata);
992 }
993
994 pub fn apply_internal_user_metadata(&mut self, metadata: InternalUserMetadata) {
996 self.vars.set_internal_user_metadata(metadata);
997 }
998
999 pub fn initialize_role_metadata(&mut self, role_id: RoleId) {
1001 self.role_metadata = Some(RoleMetadata::new(role_id));
1002 }
1003
1004 pub fn ensure_timestamp_oracle(&mut self, timeline: Timeline) -> &mut InMemoryTimestampOracle {
1007 self.session_oracles.entry(timeline).or_insert_with(|| {
1008 InMemoryTimestampOracle::new(Timestamp::minimum(), NowFn::from(Timestamp::minimum))
1009 })
1010 }
1011
1012 pub fn ensure_local_timestamp_oracle(&mut self) -> &mut InMemoryTimestampOracle {
1015 self.ensure_timestamp_oracle(Timeline::EpochMilliseconds)
1016 }
1017
1018 pub fn get_timestamp_oracle(&self, timeline: &Timeline) -> Option<&InMemoryTimestampOracle> {
1020 self.session_oracles.get(timeline)
1021 }
1022
1023 pub fn apply_write(&mut self, timestamp: Timestamp) {
1026 if self.vars().transaction_isolation() == &IsolationLevel::StrongSessionSerializable {
1027 self.ensure_local_timestamp_oracle().apply_write(timestamp);
1028 }
1029 }
1030
1031 pub fn metrics(&self) -> &SessionMetrics {
1033 &self.metrics
1034 }
1035
1036 pub fn set_builtin_table_updates(&mut self, fut: BuiltinTableAppendNotify) {
1038 let prev = self.builtin_updates.replace(fut);
1039 mz_ore::soft_assert_or_log!(prev.is_none(), "replacing old builtin table notify");
1040 }
1041
1042 pub fn clear_builtin_table_updates(&mut self) -> Option<impl Future<Output = ()> + 'static> {
1045 if let Some(fut) = self.builtin_updates.take() {
1046 let histogram = self
1048 .metrics()
1049 .session_startup_table_writes_seconds()
1050 .clone();
1051 Some(async move {
1052 fut.wall_time().observe(histogram).await;
1053 })
1054 } else {
1055 None
1056 }
1057 }
1058
1059 pub fn state_revision(&self) -> u64 {
1062 self.state_revision
1063 }
1064
1065 pub(crate) fn advance_state_revision(&mut self) {
1067 self.state_revision += 1;
1068 }
1069
1070 fn advance_state_revision_for_insert(&mut self, mut verified: StateRevision) -> StateRevision {
1073 let was_current = verified.session_state_revision == self.state_revision;
1074 self.state_revision += 1;
1075 if was_current {
1077 verified.session_state_revision = self.state_revision;
1078 }
1079 verified
1080 }
1081}
1082
1083#[derive(Derivative, Clone)]
1085#[derivative(Debug)]
1086pub struct PreparedStatement {
1087 stmt: Option<Statement<Raw>>,
1088 desc: StatementDesc,
1089 pub state_revision: StateRevision,
1091 #[derivative(Debug = "ignore")]
1092 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
1093}
1094
1095impl PreparedStatement {
1096 pub fn stmt(&self) -> Option<&Statement<Raw>> {
1099 self.stmt.as_ref()
1100 }
1101
1102 pub fn desc(&self) -> &StatementDesc {
1104 &self.desc
1105 }
1106
1107 pub fn logging(&self) -> &Arc<QCell<PreparedStatementLoggingInfo>> {
1109 &self.logging
1110 }
1111}
1112
1113#[derive(Derivative)]
1115#[derivative(Debug)]
1116pub struct Portal {
1117 pub stmt: Option<Arc<Statement<Raw>>>,
1119 pub desc: StatementDesc,
1121 pub state_revision: StateRevision,
1123 pub parameters: Params,
1125 pub result_formats: Vec<Format>,
1127 #[derivative(Debug = "ignore")]
1129 pub logging: Arc<QCell<PreparedStatementLoggingInfo>>,
1130 #[derivative(Debug = "ignore")]
1132 pub state: PortalState,
1133 pub lifecycle_timestamps: Option<LifecycleTimestamps>,
1135}
1136
1137pub struct PortalRefMut<'a> {
1142 pub stmt: &'a Option<Arc<Statement<Raw>>>,
1144 pub desc: &'a StatementDesc,
1146 pub state_revision: &'a mut StateRevision,
1148 pub parameters: &'a mut Params,
1150 pub result_formats: &'a mut Vec<Format>,
1152 pub logging: &'a mut Arc<QCell<PreparedStatementLoggingInfo>>,
1154 pub state: &'a mut PortalState,
1156 pub lifecycle_timestamps: &'a mut Option<LifecycleTimestamps>,
1158}
1159
1160#[derive(Debug, Clone, Copy, PartialEq)]
1164pub struct StateRevision {
1165 pub catalog_revision: u64,
1167 pub session_state_revision: u64,
1169}
1170
1171pub enum PortalState {
1173 NotStarted,
1175 InProgress(Option<InProgressRows>),
1178 Completed(Option<String>),
1182}
1183
1184pub struct InProgressRows {
1186 pub current: Option<Box<dyn RowIterator + Send + Sync>>,
1188 pub remaining: RecordFirstRowStream,
1190}
1191
1192impl InProgressRows {
1193 pub fn new(remaining: RecordFirstRowStream) -> Self {
1195 Self {
1196 current: None,
1197 remaining,
1198 }
1199 }
1200
1201 pub fn no_more_rows(&self) -> bool {
1204 self.remaining.no_more_rows && self.current.is_none()
1205 }
1206}
1207
1208pub type RowBatchStream = Box<dyn futures::Stream<Item = PeekResponseUnary> + Unpin + Send + Sync>;
1216
1217#[derive(Debug, Clone)]
1220pub struct LifecycleTimestamps {
1221 pub received: EpochMillis,
1226}
1227
1228impl LifecycleTimestamps {
1229 pub fn new(received: EpochMillis) -> Self {
1231 Self { received }
1232 }
1233}
1234
1235#[derive(Debug)]
1239pub enum TransactionStatus {
1240 Default,
1242 Started(Transaction),
1251 InTransaction(Transaction),
1253 InTransactionImplicit(Transaction),
1256 Failed(Transaction),
1258}
1259
1260impl TransactionStatus {
1261 pub fn into_ops(self) -> Option<TransactionOps> {
1263 match self {
1264 TransactionStatus::Default | TransactionStatus::Failed(_) => None,
1265 TransactionStatus::Started(txn)
1266 | TransactionStatus::InTransaction(txn)
1267 | TransactionStatus::InTransactionImplicit(txn) => Some(txn.ops),
1268 }
1269 }
1270
1271 pub fn inner(&self) -> Option<&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 pub fn inner_mut(&mut self) -> Option<&mut Transaction> {
1284 match self {
1285 TransactionStatus::Default => None,
1286 TransactionStatus::Started(txn)
1287 | TransactionStatus::InTransaction(txn)
1288 | TransactionStatus::InTransactionImplicit(txn)
1289 | TransactionStatus::Failed(txn) => Some(txn),
1290 }
1291 }
1292
1293 fn can_retain_ddl_inspections(&self) -> bool {
1299 match self {
1300 Self::Started(txn) | Self::InTransaction(txn) | Self::InTransactionImplicit(txn) => {
1301 !txn.contains_explain
1302 && match txn.ops {
1303 TransactionOps::None | TransactionOps::DDL { .. } => true,
1304 TransactionOps::Peeks { .. }
1305 | TransactionOps::Writes(_)
1306 | TransactionOps::Subscribe
1307 | TransactionOps::SingleStatement { .. } => false,
1308 }
1309 }
1310 Self::Default | Self::Failed(_) => false,
1311 }
1312 }
1313
1314 pub(crate) fn record_explain(&mut self) -> Result<(), AdapterError> {
1316 let txn = self.inner_mut().expect("active transaction");
1317 if matches!(txn.ops, TransactionOps::DDL { .. }) {
1318 return Err(AdapterError::DDLOnlyTransaction);
1319 }
1320 txn.contains_explain = true;
1323 txn.pending_ddl_inspections.clear();
1324 Ok(())
1325 }
1326
1327 pub fn is_ddl(&self) -> bool {
1329 match self {
1330 TransactionStatus::Default => false,
1331 TransactionStatus::Started(txn)
1332 | TransactionStatus::InTransaction(txn)
1333 | TransactionStatus::InTransactionImplicit(txn)
1334 | TransactionStatus::Failed(txn) => {
1335 matches!(txn.ops, TransactionOps::DDL { .. })
1336 }
1337 }
1338 }
1339
1340 pub fn is_implicit(&self) -> bool {
1343 match self {
1344 TransactionStatus::Started(_) | TransactionStatus::InTransactionImplicit(_) => true,
1345 TransactionStatus::Default
1346 | TransactionStatus::InTransaction(_)
1347 | TransactionStatus::Failed(_) => false,
1348 }
1349 }
1350
1351 pub fn may_span_pipeline(&self) -> bool {
1359 match self {
1360 TransactionStatus::Started(txn) => match &txn.ops {
1361 TransactionOps::Writes(_) => true,
1362 TransactionOps::None
1363 | TransactionOps::Peeks { .. }
1364 | TransactionOps::Subscribe
1365 | TransactionOps::SingleStatement { .. }
1366 | TransactionOps::DDL { .. } => false,
1367 },
1368 TransactionStatus::Default
1369 | TransactionStatus::InTransaction(_)
1370 | TransactionStatus::InTransactionImplicit(_)
1371 | TransactionStatus::Failed(_) => false,
1372 }
1373 }
1374
1375 pub fn is_in_multi_statement_transaction(&self) -> bool {
1377 match self {
1378 TransactionStatus::InTransaction(_) | TransactionStatus::InTransactionImplicit(_) => {
1379 true
1380 }
1381 TransactionStatus::Default
1382 | TransactionStatus::Started(_)
1383 | TransactionStatus::Failed(_) => false,
1384 }
1385 }
1386
1387 pub fn may_share_transaction_with_other_statements(&self) -> bool {
1407 self.is_in_multi_statement_transaction() || self.contains_ops()
1408 }
1409
1410 pub fn in_immediate_multi_stmt_txn(&self, when: &QueryWhen) -> bool {
1412 self.is_in_multi_statement_transaction() && when == &QueryWhen::Immediately
1413 }
1414
1415 pub fn timeline(&self) -> Option<Timeline> {
1417 match self {
1418 TransactionStatus::Default => None,
1419 TransactionStatus::Started(txn)
1420 | TransactionStatus::InTransaction(txn)
1421 | TransactionStatus::InTransactionImplicit(txn)
1422 | TransactionStatus::Failed(txn) => txn.timeline(),
1423 }
1424 }
1425
1426 pub fn cluster(&self) -> Option<ClusterId> {
1428 match self {
1429 TransactionStatus::Default => None,
1430 TransactionStatus::Started(txn)
1431 | TransactionStatus::InTransaction(txn)
1432 | TransactionStatus::InTransactionImplicit(txn)
1433 | TransactionStatus::Failed(txn) => txn.cluster(),
1434 }
1435 }
1436
1437 pub fn catalog_state(&self) -> Option<&CatalogState> {
1439 match self.inner() {
1440 Some(Transaction {
1441 ops: TransactionOps::DDL { state, .. },
1442 ..
1443 }) => Some(state),
1444 _ => None,
1445 }
1446 }
1447
1448 pub fn contains_ops(&self) -> bool {
1450 match self.inner() {
1451 Some(txn) => txn.contains_ops(),
1452 None => false,
1453 }
1454 }
1455
1456 pub fn allows_writes(&self) -> bool {
1459 match self {
1460 TransactionStatus::Started(Transaction { ops, access, .. })
1461 | TransactionStatus::InTransaction(Transaction { ops, access, .. })
1462 | TransactionStatus::InTransactionImplicit(Transaction { ops, access, .. }) => {
1463 match ops {
1464 TransactionOps::None => access != &Some(TransactionAccessMode::ReadOnly),
1465 TransactionOps::Peeks { determination, .. } => {
1466 access != &Some(TransactionAccessMode::ReadOnly)
1471 && !determination.timestamp_context.contains_timestamp()
1472 }
1473 TransactionOps::Subscribe => false,
1474 TransactionOps::Writes(_) => true,
1475 TransactionOps::SingleStatement { .. } => false,
1476 TransactionOps::DDL { .. } => false,
1477 }
1478 }
1479 TransactionStatus::Default | TransactionStatus::Failed(_) => {
1480 unreachable!()
1481 }
1482 }
1483 }
1484
1485 pub fn add_ops(&mut self, mut add_ops: TransactionOps) -> Result<(), AdapterError> {
1498 if matches!(add_ops, TransactionOps::DDL { .. })
1499 && self.inner().is_some_and(|txn| txn.contains_explain)
1500 {
1501 return Err(AdapterError::DDLOnlyTransaction);
1502 }
1503 match self {
1504 TransactionStatus::Started(Transaction {
1505 ops,
1506 access,
1507 pending_ddl_inspections,
1508 ..
1509 })
1510 | TransactionStatus::InTransaction(Transaction {
1511 ops,
1512 access,
1513 pending_ddl_inspections,
1514 ..
1515 })
1516 | TransactionStatus::InTransactionImplicit(Transaction {
1517 ops,
1518 access,
1519 pending_ddl_inspections,
1520 ..
1521 }) => {
1522 match ops {
1523 TransactionOps::None => {
1524 if matches!(access, Some(TransactionAccessMode::ReadOnly))
1525 && matches!(add_ops, TransactionOps::Writes(_))
1526 {
1527 return Err(AdapterError::ReadOnlyTransaction);
1528 }
1529 match &mut add_ops {
1530 TransactionOps::DDL { commands, .. } => {
1531 commands.splice(
1534 0..0,
1535 pending_ddl_inspections
1536 .drain(..)
1537 .map(DdlInspection::into_command),
1538 );
1539 }
1540 TransactionOps::None => {}
1541 TransactionOps::Peeks { .. }
1542 | TransactionOps::Writes(_)
1543 | TransactionOps::Subscribe
1544 | TransactionOps::SingleStatement { .. } => {
1545 pending_ddl_inspections.clear();
1546 }
1547 }
1548 *ops = add_ops;
1549 }
1550 TransactionOps::Peeks {
1551 determination,
1552 cluster_id,
1553 requires_linearization,
1554 } => match add_ops {
1555 TransactionOps::Peeks {
1556 determination: add_timestamp_determination,
1557 cluster_id: add_cluster_id,
1558 requires_linearization: add_requires_linearization,
1559 } => {
1560 assert_eq!(*cluster_id, add_cluster_id);
1561 match (
1562 &determination.timestamp_context,
1563 &add_timestamp_determination.timestamp_context,
1564 ) {
1565 (
1566 TimestampContext::TimelineTimestamp {
1567 timeline: txn_timeline,
1568 chosen_ts: txn_ts,
1569 oracle_ts: _,
1570 },
1571 TimestampContext::TimelineTimestamp {
1572 timeline: add_timeline,
1573 chosen_ts: add_ts,
1574 oracle_ts: _,
1575 },
1576 ) => {
1577 assert_eq!(txn_timeline, add_timeline);
1578 assert_eq!(txn_ts, add_ts);
1579 }
1580 (TimestampContext::NoTimestamp, _) => {
1581 *determination = add_timestamp_determination
1582 }
1583 (_, TimestampContext::NoTimestamp) => {}
1584 };
1585 if matches!(requires_linearization, RequireLinearization::NotRequired)
1586 && matches!(
1587 add_requires_linearization,
1588 RequireLinearization::Required
1589 )
1590 {
1591 *requires_linearization = add_requires_linearization;
1592 }
1593 }
1594 writes @ TransactionOps::Writes(..)
1603 if !determination.timestamp_context.contains_timestamp() =>
1604 {
1605 if matches!(access, Some(TransactionAccessMode::ReadOnly)) {
1606 return Err(AdapterError::ReadOnlyTransaction);
1607 }
1608 *ops = writes;
1609 }
1610 _ => return Err(AdapterError::ReadOnlyTransaction),
1611 },
1612 TransactionOps::Subscribe => {
1613 return Err(AdapterError::SubscribeOnlyTransaction);
1614 }
1615 TransactionOps::Writes(txn_writes) => match add_ops {
1616 TransactionOps::Writes(mut add_writes) => {
1617 assert!(!matches!(access, Some(TransactionAccessMode::ReadOnly)));
1620 txn_writes.append(&mut add_writes);
1621 }
1622 TransactionOps::Peeks { determination, .. }
1625 if !determination.timestamp_context.contains_timestamp() => {}
1626 _ => {
1627 return Err(AdapterError::WriteOnlyTransaction);
1628 }
1629 },
1630 TransactionOps::SingleStatement { .. } => {
1631 return Err(AdapterError::SingleStatementTransaction);
1632 }
1633 TransactionOps::DDL {
1634 commands,
1635 state,
1636 snapshot,
1637 } => match add_ops {
1638 TransactionOps::DDL {
1639 commands: new_commands,
1640 state: new_state,
1641 snapshot: new_snapshot,
1642 } => {
1643 if !new_commands.is_empty() {
1644 commands.extend(new_commands);
1645 *state = new_state;
1646 *snapshot = new_snapshot;
1647 }
1648 }
1649 _ => return Err(AdapterError::DDLOnlyTransaction),
1650 },
1651 }
1652 }
1653 TransactionStatus::Default | TransactionStatus::Failed(_) => {
1654 unreachable!()
1655 }
1656 }
1657 Ok(())
1658 }
1659}
1660
1661pub type TransactionId = u64;
1663
1664impl Default for TransactionStatus {
1665 fn default() -> Self {
1666 TransactionStatus::Default
1667 }
1668}
1669
1670#[derive(Debug)]
1677enum DdlInspection {
1678 CatalogResult(Arc<crate::catalog::command::CatalogResultCommand>),
1679 Description(Arc<crate::catalog::command::DescriptionCommand>),
1680}
1681
1682impl DdlInspection {
1683 fn into_command(self) -> crate::catalog::command::CatalogCommand {
1684 match self {
1685 Self::CatalogResult(command) => {
1686 crate::catalog::command::CatalogCommand::CatalogResult(command)
1687 }
1688 Self::Description(command) => {
1689 crate::catalog::command::CatalogCommand::Description(command)
1690 }
1691 }
1692 }
1693}
1694
1695#[derive(Debug)]
1697pub struct Transaction {
1698 completion_owner: TransactionCompletionOwner,
1699 pub pcx: PlanContext,
1701 pub ops: TransactionOps,
1703 pending_ddl_inspections: Vec<DdlInspection>,
1705 contains_explain: bool,
1706 pub id: TransactionId,
1711 access: Option<TransactionAccessMode>,
1713}
1714
1715#[derive(Debug, PartialEq)]
1716enum TransactionCompletionOwner {
1717 Session,
1718 Coordinator,
1719}
1720
1721pub(crate) struct ReadOnlyCompletion {
1723 pub action: EndTransactionAction,
1724 pub timestamp: Option<TimestampContext>,
1725}
1726
1727impl Transaction {
1728 fn timeline(&self) -> Option<Timeline> {
1730 match &self.ops {
1731 TransactionOps::Peeks {
1732 determination:
1733 TimestampDetermination {
1734 timestamp_context: TimestampContext::TimelineTimestamp { timeline, .. },
1735 ..
1736 },
1737 ..
1738 } => Some(timeline.clone()),
1739 TransactionOps::Peeks { .. }
1740 | TransactionOps::None
1741 | TransactionOps::Subscribe
1742 | TransactionOps::Writes(_)
1743 | TransactionOps::SingleStatement { .. }
1744 | TransactionOps::DDL { .. } => None,
1745 }
1746 }
1747
1748 pub fn cluster(&self) -> Option<ClusterId> {
1750 match &self.ops {
1751 TransactionOps::Peeks { cluster_id, .. } => Some(cluster_id.clone()),
1752 TransactionOps::None
1753 | TransactionOps::Subscribe
1754 | TransactionOps::Writes(_)
1755 | TransactionOps::SingleStatement { .. }
1756 | TransactionOps::DDL { .. } => None,
1757 }
1758 }
1759
1760 fn contains_ops(&self) -> bool {
1762 !matches!(self.ops, TransactionOps::None)
1763 }
1764}
1765
1766#[derive(Debug, Clone, Copy)]
1768pub enum TransactionCode {
1769 Idle,
1771 InTransaction,
1773 Failed,
1775}
1776
1777impl From<TransactionCode> for u8 {
1778 fn from(code: TransactionCode) -> Self {
1779 match code {
1780 TransactionCode::Idle => b'I',
1781 TransactionCode::InTransaction => b'T',
1782 TransactionCode::Failed => b'E',
1783 }
1784 }
1785}
1786
1787impl From<TransactionCode> for String {
1788 fn from(code: TransactionCode) -> Self {
1789 char::from(u8::from(code)).to_string()
1790 }
1791}
1792
1793impl From<&TransactionStatus> for TransactionCode {
1794 fn from(status: &TransactionStatus) -> TransactionCode {
1796 match status {
1797 TransactionStatus::Default => TransactionCode::Idle,
1798 TransactionStatus::Started(_) => TransactionCode::InTransaction,
1799 TransactionStatus::InTransaction(_) => TransactionCode::InTransaction,
1800 TransactionStatus::InTransactionImplicit(_) => TransactionCode::InTransaction,
1801 TransactionStatus::Failed(_) => TransactionCode::Failed,
1802 }
1803 }
1804}
1805
1806#[derive(Derivative)]
1812#[derivative(Debug)]
1813pub enum TransactionOps {
1814 None,
1817 Peeks {
1822 determination: TimestampDetermination,
1824 cluster_id: ClusterId,
1826 requires_linearization: RequireLinearization,
1828 },
1829 Subscribe,
1831 Writes(Vec<WriteOp>),
1834 SingleStatement {
1836 stmt: Arc<Statement<Raw>>,
1838 params: mz_sql::plan::Params,
1840 },
1841 DDL {
1845 commands: Vec<crate::catalog::command::CatalogCommand>,
1847 state: CatalogState,
1849 snapshot: Snapshot,
1851 },
1852}
1853
1854impl TransactionOps {
1855 pub fn stages_work(&self) -> bool {
1859 matches!(
1860 self,
1861 TransactionOps::Writes(_)
1862 | TransactionOps::DDL { .. }
1863 | TransactionOps::SingleStatement { .. }
1864 )
1865 }
1866}
1867
1868impl Default for TransactionOps {
1869 fn default() -> Self {
1870 Self::None
1871 }
1872}
1873
1874#[derive(Debug, Clone, PartialEq)]
1876pub struct WriteOp {
1877 pub id: CatalogItemId,
1879 pub rows: TableData,
1881}
1882
1883#[derive(Debug)]
1885pub enum RequireLinearization {
1886 Required,
1888 NotRequired,
1890}
1891
1892impl From<&ExplainContext> for RequireLinearization {
1893 fn from(ctx: &ExplainContext) -> Self {
1894 match ctx {
1895 ExplainContext::None | ExplainContext::PlanInsightsNotice(_) => {
1896 RequireLinearization::Required
1897 }
1898 ExplainContext::Plan(_) | ExplainContext::Pushdown | ExplainContext::Timestamp => {
1899 RequireLinearization::NotRequired
1900 }
1901 }
1902 }
1903}
1904#[cfg(test)]
1905mod tests {
1906 use super::*;
1907 use mz_sql::session::vars::{SystemVars, VarInput};
1908 use timely::progress::Antichain;
1909
1910 fn read_session() -> Session {
1911 let mut session = Session::dummy();
1912 session.start_transaction_single_stmt(Utc::now());
1913 session
1914 .add_transaction_ops(TransactionOps::Peeks {
1915 determination: TimestampDetermination {
1916 timestamp_context: TimestampContext::TimelineTimestamp {
1917 timeline: Timeline::EpochMilliseconds,
1918 chosen_ts: 10.into(),
1919 oracle_ts: Some(10.into()),
1920 },
1921 since: Antichain::from_elem(0.into()),
1922 upper: Antichain::new(),
1923 largest_not_in_advance_of_upper: Timestamp::MAX,
1924 oracle_read_ts: Some(10.into()),
1925 session_oracle_read_ts: None,
1926 real_time_recency_ts: None,
1927 constraints: Default::default(),
1928 },
1929 cluster_id: ClusterId::User(1),
1930 requires_linearization: RequireLinearization::Required,
1931 })
1932 .expect("read transaction");
1933 session
1934 }
1935
1936 #[mz_ore::test]
1937 fn read_completion_tracks_ownership_not_just_ops() {
1938 let mut session = read_session();
1939 let completion = session
1940 .read_only_completion(EndTransactionAction::Commit)
1941 .expect("local read");
1942 assert_eq!(completion.action, EndTransactionAction::Commit);
1943 assert!(completion.timestamp.is_some());
1944 session.require_coordinator_completion();
1945 assert!(
1946 session
1947 .read_only_completion(EndTransactionAction::Commit)
1948 .is_none()
1949 );
1950 let _ = session.clear_transaction();
1951 session.start_transaction_single_stmt(Utc::now());
1952 assert!(
1953 session
1954 .read_only_completion(EndTransactionAction::Commit)
1955 .is_some()
1956 );
1957 }
1958
1959 #[mz_ore::test]
1960 fn completion_skips_timestamp_for_failed_and_rolled_back_reads() {
1961 let session = read_session();
1962 let rollback = session
1963 .read_only_completion(EndTransactionAction::Rollback)
1964 .expect("local read");
1965 assert!(rollback.timestamp.is_none());
1966 let session = session.fail_transaction();
1967 let failed = session
1968 .read_only_completion(EndTransactionAction::Commit)
1969 .expect("failed local read");
1970 assert_eq!(failed.action, EndTransactionAction::Rollback);
1971 assert!(failed.timestamp.is_none());
1972 }
1973
1974 #[mz_ore::test]
1975 fn completion_rejects_resource_bearing_transactions() {
1976 for ops in [
1977 TransactionOps::Subscribe,
1978 TransactionOps::Writes(Vec::new()),
1979 ] {
1980 let mut session = Session::dummy();
1981 session.start_transaction_single_stmt(Utc::now());
1982 session.add_transaction_ops(ops).expect("first operation");
1983 assert!(
1984 session
1985 .read_only_completion(EndTransactionAction::Commit)
1986 .is_none()
1987 );
1988 assert!(
1989 session
1990 .fail_transaction()
1991 .read_only_completion(EndTransactionAction::Rollback)
1992 .is_none()
1993 );
1994 }
1995 }
1996
1997 #[mz_ore::test]
1998 fn read_completion_preserves_transactional_parameter_changes() {
1999 for action in [EndTransactionAction::Commit, EndTransactionAction::Rollback] {
2000 let mut session = read_session();
2001 session
2002 .vars_mut()
2003 .set_default("application_name", VarInput::Flat("session"))
2004 .expect("default");
2005 session
2006 .vars_mut()
2007 .set(
2008 &SystemVars::new(),
2009 "application_name",
2010 VarInput::Flat("local"),
2011 true,
2012 )
2013 .expect("local setting");
2014 let completion = session.read_only_completion(action).expect("local read");
2015 let _ = session.clear_transaction();
2016 let params = session.vars_mut().end_transaction(completion.action);
2017 assert_eq!(
2018 params.get("application_name").map(String::as_str),
2019 Some("session")
2020 );
2021 assert_eq!(session.vars().application_name(), "session");
2022 assert!(matches!(session.transaction(), TransactionStatus::Default));
2023 }
2024 }
2025
2026 #[mz_ore::test]
2027 fn ddl_inspections_are_released_when_ddl_becomes_impossible() {
2028 use mz_sql::plan::{Params, StatementDesc};
2029 use timely::progress::Antichain;
2030
2031 let statement = mz_sql_parser::parser::parse_statements("SELECT 1")
2032 .expect("valid SQL")
2033 .remove(0)
2034 .ast;
2035 let modes = [
2036 TransactionOps::Peeks {
2037 determination: TimestampDetermination {
2038 timestamp_context: TimestampContext::NoTimestamp,
2039 since: Antichain::new(),
2040 upper: Antichain::new(),
2041 largest_not_in_advance_of_upper: mz_repr::Timestamp::MIN,
2042 oracle_read_ts: None,
2043 session_oracle_read_ts: None,
2044 real_time_recency_ts: None,
2045 constraints: Default::default(),
2046 },
2047 cluster_id: mz_controller_types::ClusterId::User(1),
2048 requires_linearization: RequireLinearization::NotRequired,
2049 },
2050 TransactionOps::Writes(vec![]),
2051 TransactionOps::Subscribe,
2052 TransactionOps::SingleStatement {
2053 stmt: Arc::new(statement.clone()),
2054 params: Params::empty(),
2055 },
2056 ];
2057 for mode in modes.into_iter().map(Some).chain([None]) {
2059 let mut session = Session::dummy();
2060 session.start_transaction_implicit(Utc::now(), 2);
2061 let command = Arc::new(crate::catalog::command::DescriptionCommand::new(
2062 statement.clone(),
2063 vec![],
2064 session.meta(),
2065 StatementDesc::new(Some(mz_repr::RelationDesc::empty())),
2066 ));
2067 let retained = Arc::downgrade(&command);
2068 session.retain_ddl_inspection(DdlInspection::Description(command));
2069 assert!(retained.upgrade().is_some(), "DDL is still possible");
2070 if let Some(mode) = mode {
2071 session.add_transaction_ops(mode).expect("valid transition");
2072 } else {
2073 session
2074 .transaction_mut()
2075 .record_explain()
2076 .expect("EXPLAIN allowed");
2077 }
2078 assert!(retained.upgrade().is_none(), "release earlier inspections");
2079 let command = Arc::new(crate::catalog::command::DescriptionCommand::new(
2080 statement.clone(),
2081 vec![],
2082 session.meta(),
2083 StatementDesc::new(Some(mz_repr::RelationDesc::empty())),
2084 ));
2085 let discarded = Arc::downgrade(&command);
2086 session.retain_ddl_inspection(DdlInspection::Description(command));
2087 assert!(
2088 discarded.upgrade().is_none(),
2089 "do not retain later inspections"
2090 );
2091 }
2092 }
2093}