1#![warn(missing_docs)]
13
14use std::collections::btree_map::Entry;
15use std::collections::{BTreeMap, BTreeSet};
16use std::fmt::Debug;
17use std::future::Future;
18use std::mem;
19use std::net::IpAddr;
20use std::sync::Arc;
21
22use chrono::{DateTime, Utc};
23use derivative::Derivative;
24use itertools::Itertools;
25use mz_adapter_types::connection::ConnectionId;
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::{ExternalUserMetadata, InternalUserMetadata};
33use mz_repr::{CatalogItemId, Datum, Row, RowIterator, ScalarType, TimestampManipulation};
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 rand::Rng;
50use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
51use tokio::sync::watch;
52use uuid::Uuid;
53
54use crate::AdapterNotice;
55use crate::catalog::CatalogState;
56use crate::client::RecordFirstRowStream;
57use crate::coord::ExplainContext;
58use crate::coord::appends::BuiltinTableAppendNotify;
59use crate::coord::in_memory_oracle::InMemoryTimestampOracle;
60use crate::coord::peek::PeekResponseUnary;
61use crate::coord::statement_logging::PreparedStatementLoggingInfo;
62use crate::coord::timestamp_selection::{TimestampContext, TimestampDetermination};
63use crate::error::AdapterError;
64use crate::metrics::{Metrics, SessionMetrics};
65
66const DUMMY_CONNECTION_ID: ConnectionId = ConnectionId::Static(0);
67
68#[derive(Derivative)]
70#[derivative(Debug)]
71pub struct Session<T = mz_repr::Timestamp>
72where
73 T: Debug + Clone + Send + Sync,
74{
75 conn_id: ConnectionId,
76 uuid: Uuid,
79 prepared_statements: BTreeMap<String, PreparedStatement>,
80 portals: BTreeMap<String, Portal>,
81 transaction: TransactionStatus<T>,
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<T, NowFn<T>>>,
121}
122
123impl<T> SessionMetadata for Session<T>
124where
125 T: Debug + Clone + Send + Sync,
126 T: TimestampManipulation,
127{
128 fn conn_id(&self) -> &ConnectionId {
129 &self.conn_id
130 }
131
132 fn client_ip(&self) -> Option<&IpAddr> {
133 self.client_ip.as_ref()
134 }
135
136 fn pcx(&self) -> &PlanContext {
137 &self
138 .transaction()
139 .inner()
140 .expect("no active transaction")
141 .pcx
142 }
143
144 fn role_metadata(&self) -> &RoleMetadata {
145 self.role_metadata
146 .as_ref()
147 .expect("role_metadata invariant violated")
148 }
149
150 fn vars(&self) -> &SessionVars {
151 &self.vars
152 }
153}
154
155#[derive(Debug)]
158pub struct SessionMeta {
159 conn_id: ConnectionId,
160 client_ip: Option<IpAddr>,
161 pcx: PlanContext,
162 role_metadata: RoleMetadata,
163 vars: SessionVars,
164}
165
166impl SessionMetadata for SessionMeta {
167 fn vars(&self) -> &SessionVars {
168 &self.vars
169 }
170
171 fn conn_id(&self) -> &ConnectionId {
172 &self.conn_id
173 }
174
175 fn client_ip(&self) -> Option<&IpAddr> {
176 self.client_ip.as_ref()
177 }
178
179 fn pcx(&self) -> &PlanContext {
180 &self.pcx
181 }
182
183 fn role_metadata(&self) -> &RoleMetadata {
184 &self.role_metadata
185 }
186}
187
188#[derive(Debug, Clone)]
190pub struct SessionConfig {
191 pub conn_id: ConnectionId,
195 pub uuid: Uuid,
200 pub client_ip: Option<IpAddr>,
202 pub user: String,
204 pub external_metadata_rx: Option<watch::Receiver<ExternalUserMetadata>>,
207 pub internal_user_metadata: Option<InternalUserMetadata>,
209 pub helm_chart_version: Option<String>,
211}
212
213impl<T: TimestampManipulation> Session<T> {
214 pub(crate) fn new(
216 build_info: &'static BuildInfo,
217 config: SessionConfig,
218 metrics: SessionMetrics,
219 ) -> Session<T> {
220 assert_ne!(config.conn_id, DUMMY_CONNECTION_ID);
221 Self::new_internal(build_info, config, metrics)
222 }
223
224 pub fn meta(&self) -> SessionMeta {
227 SessionMeta {
228 conn_id: self.conn_id().clone(),
229 client_ip: self.client_ip().copied(),
230 pcx: self.pcx().clone(),
231 role_metadata: self.role_metadata().clone(),
232 vars: self.vars.clone(),
233 }
234
235 }
237
238 pub(crate) fn mint_logging<A: AstInfo>(
248 &self,
249 raw_sql: String,
250 stmt: Option<&Statement<A>>,
251 now: EpochMillis,
252 ) -> Arc<QCell<PreparedStatementLoggingInfo>> {
253 Arc::new(QCell::new(
254 &self.qcell_owner,
255 PreparedStatementLoggingInfo::still_to_log(
256 raw_sql,
257 stmt,
258 now,
259 "".to_string(),
260 self.uuid,
261 false,
262 ),
263 ))
264 }
265
266 pub(crate) fn qcell_rw<'a, T2: 'a>(&'a mut self, cell: &'a Arc<QCell<T2>>) -> &'a mut T2 {
267 self.qcell_owner.rw(&*cell)
268 }
269
270 pub fn uuid(&self) -> Uuid {
273 self.uuid
274 }
275
276 pub fn dummy() -> Session<T> {
281 let registry = MetricsRegistry::new();
282 let metrics = Metrics::register_into(®istry);
283 let metrics = metrics.session_metrics();
284 let mut dummy = Self::new_internal(
285 &DUMMY_BUILD_INFO,
286 SessionConfig {
287 conn_id: DUMMY_CONNECTION_ID,
288 uuid: Uuid::new_v4(),
289 user: SYSTEM_USER.name.clone(),
290 client_ip: None,
291 external_metadata_rx: None,
292 internal_user_metadata: None,
293 helm_chart_version: None,
294 },
295 metrics,
296 );
297 dummy.initialize_role_metadata(RoleId::User(0));
298 dummy
299 }
300
301 fn new_internal(
302 build_info: &'static BuildInfo,
303 SessionConfig {
304 conn_id,
305 uuid,
306 user,
307 client_ip,
308 mut external_metadata_rx,
309 internal_user_metadata,
310 helm_chart_version,
311 }: SessionConfig,
312 metrics: SessionMetrics,
313 ) -> Session<T> {
314 let (notices_tx, notices_rx) = mpsc::unbounded_channel();
315 let default_cluster = INTERNAL_USER_NAME_TO_DEFAULT_CLUSTER.get(&user);
316 let user = User {
317 name: user,
318 internal_metadata: internal_user_metadata,
319 external_metadata: external_metadata_rx
320 .as_mut()
321 .map(|rx| rx.borrow_and_update().clone()),
322 };
323 let mut vars = SessionVars::new_unchecked(build_info, user, helm_chart_version);
324 if let Some(default_cluster) = default_cluster {
325 vars.set_cluster(default_cluster.clone());
326 }
327 Session {
328 conn_id,
329 uuid,
330 transaction: TransactionStatus::Default,
331 pcx: None,
332 metrics,
333 builtin_updates: None,
334 prepared_statements: BTreeMap::new(),
335 portals: BTreeMap::new(),
336 role_metadata: None,
337 client_ip,
338 vars,
339 notices_tx,
340 notices_rx,
341 next_transaction_id: 0,
342 secret_key: rand::thread_rng().r#gen(),
343 external_metadata_rx,
344 qcell_owner: QCellOwner::new(),
345 session_oracles: BTreeMap::new(),
346 }
347 }
348
349 pub fn secret_key(&self) -> u32 {
351 self.secret_key
352 }
353
354 fn new_pcx(&self, mut wall_time: DateTime<Utc>) -> PlanContext {
355 if let Some(mock_time) = self.vars().unsafe_new_transaction_wall_time() {
356 wall_time = *mock_time;
357 }
358 PlanContext::new(wall_time)
359 }
360
361 pub fn start_transaction(
364 &mut self,
365 wall_time: DateTime<Utc>,
366 access: Option<TransactionAccessMode>,
367 isolation_level: Option<TransactionIsolationLevel>,
368 ) -> Result<(), AdapterError> {
369 if let Some(txn) = self.transaction.inner() {
371 let read_write_prohibited = match txn.ops {
375 TransactionOps::Peeks { .. } | TransactionOps::Subscribe => {
376 txn.access == Some(TransactionAccessMode::ReadOnly)
377 }
378 TransactionOps::None
379 | TransactionOps::Writes(_)
380 | TransactionOps::SingleStatement { .. }
381 | TransactionOps::DDL { .. } => false,
382 };
383
384 if read_write_prohibited && access == Some(TransactionAccessMode::ReadWrite) {
385 return Err(AdapterError::ReadWriteUnavailable);
386 }
387 }
388
389 match std::mem::take(&mut self.transaction) {
390 TransactionStatus::Default => {
391 let id = self.next_transaction_id;
392 self.next_transaction_id = self.next_transaction_id.wrapping_add(1);
393 self.transaction = TransactionStatus::InTransaction(Transaction {
394 pcx: self.new_pcx(wall_time),
395 ops: TransactionOps::None,
396 write_lock_guards: None,
397 access,
398 id,
399 });
400 }
401 TransactionStatus::Started(mut txn)
402 | TransactionStatus::InTransactionImplicit(mut txn)
403 | TransactionStatus::InTransaction(mut txn) => {
404 if access.is_some() {
405 txn.access = access;
406 }
407 self.transaction = TransactionStatus::InTransaction(txn);
408 }
409 TransactionStatus::Failed(_) => unreachable!(),
410 };
411
412 if let Some(isolation_level) = isolation_level {
413 self.vars
414 .set_local_transaction_isolation(isolation_level.into());
415 }
416
417 Ok(())
418 }
419
420 pub fn start_transaction_implicit(&mut self, wall_time: DateTime<Utc>, stmts: usize) {
423 if let TransactionStatus::Default = self.transaction {
424 let id = self.next_transaction_id;
425 self.next_transaction_id = self.next_transaction_id.wrapping_add(1);
426 let txn = Transaction {
427 pcx: self.new_pcx(wall_time),
428 ops: TransactionOps::None,
429 write_lock_guards: None,
430 access: None,
431 id,
432 };
433 match stmts {
434 1 => self.transaction = TransactionStatus::Started(txn),
435 n if n > 1 => self.transaction = TransactionStatus::InTransactionImplicit(txn),
436 _ => {}
437 }
438 }
439 }
440
441 pub fn start_transaction_single_stmt(&mut self, wall_time: DateTime<Utc>) {
443 self.start_transaction_implicit(wall_time, 1);
444 }
445
446 #[must_use]
456 pub fn clear_transaction(&mut self) -> TransactionStatus<T> {
457 self.portals.clear();
458 self.pcx = None;
459 mem::take(&mut self.transaction)
460 }
461
462 pub fn fail_transaction(mut self) -> Self {
464 match self.transaction {
465 TransactionStatus::Default => unreachable!(),
466 TransactionStatus::Started(txn)
467 | TransactionStatus::InTransactionImplicit(txn)
468 | TransactionStatus::InTransaction(txn) => {
469 self.transaction = TransactionStatus::Failed(txn);
470 }
471 TransactionStatus::Failed(_) => {}
472 };
473 self
474 }
475
476 pub fn transaction(&self) -> &TransactionStatus<T> {
478 &self.transaction
479 }
480
481 pub fn transaction_mut(&mut self) -> &mut TransactionStatus<T> {
483 &mut self.transaction
484 }
485
486 pub fn transaction_code(&self) -> TransactionCode {
488 self.transaction().into()
489 }
490
491 pub fn add_transaction_ops(&mut self, add_ops: TransactionOps<T>) -> Result<(), AdapterError> {
495 self.transaction.add_ops(add_ops)
496 }
497
498 pub fn retain_notice_transmitter(&self) -> UnboundedSender<AdapterNotice> {
500 self.notices_tx.clone()
501 }
502
503 pub fn add_notice(&self, notice: AdapterNotice) {
505 self.add_notices([notice])
506 }
507
508 pub fn add_notices(&self, notices: impl IntoIterator<Item = AdapterNotice>) {
510 for notice in notices {
511 let _ = self.notices_tx.send(notice);
512 }
513 }
514
515 pub async fn recv_notice(&mut self) -> AdapterNotice {
519 loop {
521 let notice = self
522 .notices_rx
523 .recv()
524 .await
525 .expect("Session also holds a sender, so recv won't ever return None");
526 match self.notice_filter(notice) {
527 Some(notice) => return notice,
528 None => continue,
529 }
530 }
531 }
532
533 pub fn drain_notices(&mut self) -> Vec<AdapterNotice> {
535 let mut notices = Vec::new();
536 while let Ok(notice) = self.notices_rx.try_recv() {
537 if let Some(notice) = self.notice_filter(notice) {
538 notices.push(notice);
539 }
540 }
541 notices
542 }
543
544 fn notice_filter(&self, notice: AdapterNotice) -> Option<AdapterNotice> {
546 let minimum_client_severity = self.vars.client_min_messages();
548 let sev = notice.severity();
549 if !minimum_client_severity.should_output_to_client(&sev) {
550 return None;
551 }
552 if let AdapterNotice::ClusterReplicaStatusChanged { cluster, .. } = ¬ice {
554 if cluster != self.vars.cluster() {
555 return None;
556 }
557 }
558 Some(notice)
559 }
560
561 pub fn clear_transaction_ops(&mut self) {
564 if let Some(txn) = self.transaction.inner_mut() {
565 txn.ops = TransactionOps::None;
566 }
567 }
568
569 pub fn take_transaction_timestamp_context(&mut self) -> Option<TimestampContext<T>> {
574 if let Some(Transaction { ops, .. }) = self.transaction.inner_mut() {
575 if let TransactionOps::Peeks { .. } = ops {
576 let ops = std::mem::take(ops);
577 Some(
578 ops.timestamp_determination()
579 .expect("checked above")
580 .timestamp_context,
581 )
582 } else {
583 None
584 }
585 } else {
586 None
587 }
588 }
589
590 pub fn get_transaction_timestamp_determination(&self) -> Option<TimestampDetermination<T>> {
595 match self.transaction.inner() {
596 Some(Transaction {
597 pcx: _,
598 ops: TransactionOps::Peeks { determination, .. },
599 write_lock_guards: _,
600 access: _,
601 id: _,
602 }) => Some(determination.clone()),
603 _ => None,
604 }
605 }
606
607 pub fn contains_read_timestamp(&self) -> bool {
609 matches!(
610 self.transaction.inner(),
611 Some(Transaction {
612 pcx: _,
613 ops: TransactionOps::Peeks {
614 determination: TimestampDetermination {
615 timestamp_context: TimestampContext::TimelineTimestamp { .. },
616 ..
617 },
618 ..
619 },
620 write_lock_guards: _,
621 access: _,
622 id: _,
623 })
624 )
625 }
626
627 pub fn set_prepared_statement(
629 &mut self,
630 name: String,
631 stmt: Option<Statement<Raw>>,
632 raw_sql: String,
633 desc: StatementDesc,
634 catalog_revision: u64,
635 now: EpochMillis,
636 ) {
637 let logging = PreparedStatementLoggingInfo::still_to_log(
638 raw_sql,
639 stmt.as_ref(),
640 now,
641 name.clone(),
642 self.uuid,
643 false,
644 );
645 let statement = PreparedStatement {
646 stmt,
647 desc,
648 catalog_revision,
649 logging: Arc::new(QCell::new(&self.qcell_owner, logging)),
650 };
651 self.prepared_statements.insert(name, statement);
652 }
653
654 pub fn remove_prepared_statement(&mut self, name: &str) -> bool {
658 self.prepared_statements.remove(name).is_some()
659 }
660
661 pub fn remove_all_prepared_statements(&mut self) {
663 self.prepared_statements.clear();
664 }
665
666 pub fn get_prepared_statement_unverified(&self, name: &str) -> Option<&PreparedStatement> {
671 self.prepared_statements.get(name)
672 }
673
674 pub fn get_prepared_statement_mut_unverified(
679 &mut self,
680 name: &str,
681 ) -> Option<&mut PreparedStatement> {
682 self.prepared_statements.get_mut(name)
683 }
684
685 pub fn prepared_statements(&self) -> &BTreeMap<String, PreparedStatement> {
687 &self.prepared_statements
688 }
689
690 pub fn set_portal(
700 &mut self,
701 portal_name: String,
702 desc: StatementDesc,
703 stmt: Option<Statement<Raw>>,
704 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
705 params: Vec<(Datum, ScalarType)>,
706 result_formats: Vec<Format>,
707 catalog_revision: u64,
708 ) -> Result<(), AdapterError> {
709 if !portal_name.is_empty() && self.portals.contains_key(&portal_name) {
711 return Err(AdapterError::DuplicateCursor(portal_name));
712 }
713 self.portals.insert(
714 portal_name,
715 Portal {
716 stmt: stmt.map(Arc::new),
717 desc,
718 catalog_revision,
719 parameters: Params {
720 datums: Row::pack(params.iter().map(|(d, _t)| d)),
721 types: params.into_iter().map(|(_d, t)| t).collect(),
722 },
723 result_formats,
724 state: PortalState::NotStarted,
725 logging,
726 },
727 );
728 Ok(())
729 }
730
731 pub fn remove_portal(&mut self, portal_name: &str) -> bool {
735 self.portals.remove(portal_name).is_some()
736 }
737
738 pub fn get_portal_unverified(&self, portal_name: &str) -> Option<&Portal> {
742 self.portals.get(portal_name)
743 }
744
745 pub fn get_portal_unverified_mut(&mut self, portal_name: &str) -> Option<&mut Portal> {
749 self.portals.get_mut(portal_name)
750 }
751
752 pub fn create_new_portal(
754 &mut self,
755 stmt: Option<Statement<Raw>>,
756 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
757 desc: StatementDesc,
758 parameters: Params,
759 result_formats: Vec<Format>,
760 catalog_revision: u64,
761 ) -> Result<String, AdapterError> {
762 for i in 0usize.. {
765 let name = format!("<unnamed portal {}>", i);
766 match self.portals.entry(name.clone()) {
767 Entry::Occupied(_) => continue,
768 Entry::Vacant(entry) => {
769 entry.insert(Portal {
770 stmt: stmt.map(Arc::new),
771 desc,
772 catalog_revision,
773 parameters,
774 result_formats,
775 state: PortalState::NotStarted,
776 logging,
777 });
778 return Ok(name);
779 }
780 }
781 }
782
783 coord_bail!("unable to create a new portal");
784 }
785
786 pub fn reset(&mut self) {
789 let _ = self.clear_transaction();
790 self.prepared_statements.clear();
791 self.vars.reset_all();
792 }
793
794 pub fn application_name(&self) -> &str {
798 self.vars.application_name()
799 }
800
801 pub fn vars(&self) -> &SessionVars {
803 &self.vars
804 }
805
806 pub fn vars_mut(&mut self) -> &mut SessionVars {
808 &mut self.vars
809 }
810
811 pub fn try_grant_write_locks(&mut self, guards: WriteLocks) -> Result<(), &WriteLocks> {
817 self.transaction.try_grant_write_locks(guards)
818 }
819
820 pub fn apply_external_metadata_updates(&mut self) {
822 let Some(rx) = &mut self.external_metadata_rx else {
824 return;
825 };
826
827 if !rx.has_changed().unwrap_or(false) {
829 return;
830 }
831
832 let metadata = rx.borrow_and_update().clone();
835 self.vars.set_external_user_metadata(metadata);
836 }
837
838 pub fn initialize_role_metadata(&mut self, role_id: RoleId) {
840 self.role_metadata = Some(RoleMetadata::new(role_id));
841 }
842
843 pub fn ensure_timestamp_oracle(
846 &mut self,
847 timeline: Timeline,
848 ) -> &mut InMemoryTimestampOracle<T, NowFn<T>> {
849 self.session_oracles
850 .entry(timeline)
851 .or_insert_with(|| InMemoryTimestampOracle::new(T::minimum(), NowFn::from(T::minimum)))
852 }
853
854 pub fn ensure_local_timestamp_oracle(&mut self) -> &mut InMemoryTimestampOracle<T, NowFn<T>> {
857 self.ensure_timestamp_oracle(Timeline::EpochMilliseconds)
858 }
859
860 pub fn get_timestamp_oracle(
862 &self,
863 timeline: &Timeline,
864 ) -> Option<&InMemoryTimestampOracle<T, NowFn<T>>> {
865 self.session_oracles.get(timeline)
866 }
867
868 pub fn apply_write(&mut self, timestamp: T) {
871 if self.vars().transaction_isolation() == &IsolationLevel::StrongSessionSerializable {
872 self.ensure_local_timestamp_oracle().apply_write(timestamp);
873 }
874 }
875
876 pub fn metrics(&self) -> &SessionMetrics {
878 &self.metrics
879 }
880
881 pub fn set_builtin_table_updates(&mut self, fut: BuiltinTableAppendNotify) {
883 let prev = self.builtin_updates.replace(fut);
884 mz_ore::soft_assert_or_log!(prev.is_none(), "replacing old builtin table notify");
885 }
886
887 pub fn clear_builtin_table_updates(&mut self) -> Option<impl Future<Output = ()> + 'static> {
890 if let Some(fut) = self.builtin_updates.take() {
891 let histogram = self
893 .metrics()
894 .session_startup_table_writes_seconds()
895 .clone();
896 Some(async move {
897 fut.wall_time().observe(histogram).await;
898 })
899 } else {
900 None
901 }
902 }
903}
904
905#[derive(Derivative, Clone)]
907#[derivative(Debug)]
908pub struct PreparedStatement {
909 stmt: Option<Statement<Raw>>,
910 desc: StatementDesc,
911 pub catalog_revision: u64,
913 #[derivative(Debug = "ignore")]
914 logging: Arc<QCell<PreparedStatementLoggingInfo>>,
915}
916
917impl PreparedStatement {
918 pub fn stmt(&self) -> Option<&Statement<Raw>> {
921 self.stmt.as_ref()
922 }
923
924 pub fn desc(&self) -> &StatementDesc {
926 &self.desc
927 }
928
929 pub fn logging(&self) -> &Arc<QCell<PreparedStatementLoggingInfo>> {
931 &self.logging
932 }
933}
934
935#[derive(Derivative)]
937#[derivative(Debug)]
938pub struct Portal {
939 pub stmt: Option<Arc<Statement<Raw>>>,
941 pub desc: StatementDesc,
943 pub catalog_revision: u64,
945 pub parameters: Params,
947 pub result_formats: Vec<Format>,
949 #[derivative(Debug = "ignore")]
951 pub logging: Arc<QCell<PreparedStatementLoggingInfo>>,
952 #[derivative(Debug = "ignore")]
954 pub state: PortalState,
955}
956
957pub enum PortalState {
959 NotStarted,
961 InProgress(Option<InProgressRows>),
964 Completed(Option<String>),
968}
969
970pub struct InProgressRows {
972 pub current: Option<Box<dyn RowIterator + Send + Sync>>,
974 pub remaining: RecordFirstRowStream,
976}
977
978impl InProgressRows {
979 pub fn new(remaining: RecordFirstRowStream) -> Self {
981 Self {
982 current: None,
983 remaining,
984 }
985 }
986}
987
988pub type RowBatchStream = UnboundedReceiver<PeekResponseUnary>;
990
991#[derive(Debug)]
995pub enum TransactionStatus<T> {
996 Default,
998 Started(Transaction<T>),
1008 InTransaction(Transaction<T>),
1010 InTransactionImplicit(Transaction<T>),
1013 Failed(Transaction<T>),
1015}
1016
1017impl<T: TimestampManipulation> TransactionStatus<T> {
1018 pub fn into_ops_and_lock_guard(self) -> (Option<TransactionOps<T>>, Option<WriteLocks>) {
1020 match self {
1021 TransactionStatus::Default | TransactionStatus::Failed(_) => (None, None),
1022 TransactionStatus::Started(txn)
1023 | TransactionStatus::InTransaction(txn)
1024 | TransactionStatus::InTransactionImplicit(txn) => {
1025 (Some(txn.ops), txn.write_lock_guards)
1026 }
1027 }
1028 }
1029
1030 pub fn inner(&self) -> Option<&Transaction<T>> {
1032 match self {
1033 TransactionStatus::Default => None,
1034 TransactionStatus::Started(txn)
1035 | TransactionStatus::InTransaction(txn)
1036 | TransactionStatus::InTransactionImplicit(txn)
1037 | TransactionStatus::Failed(txn) => Some(txn),
1038 }
1039 }
1040
1041 pub fn inner_mut(&mut self) -> Option<&mut Transaction<T>> {
1043 match self {
1044 TransactionStatus::Default => None,
1045 TransactionStatus::Started(txn)
1046 | TransactionStatus::InTransaction(txn)
1047 | TransactionStatus::InTransactionImplicit(txn)
1048 | TransactionStatus::Failed(txn) => Some(txn),
1049 }
1050 }
1051
1052 pub fn is_ddl(&self) -> bool {
1054 match self {
1055 TransactionStatus::Default => false,
1056 TransactionStatus::Started(txn)
1057 | TransactionStatus::InTransaction(txn)
1058 | TransactionStatus::InTransactionImplicit(txn)
1059 | TransactionStatus::Failed(txn) => {
1060 matches!(txn.ops, TransactionOps::DDL { .. })
1061 }
1062 }
1063 }
1064
1065 pub fn is_implicit(&self) -> bool {
1068 match self {
1069 TransactionStatus::Started(_) | TransactionStatus::InTransactionImplicit(_) => true,
1070 TransactionStatus::Default
1071 | TransactionStatus::InTransaction(_)
1072 | TransactionStatus::Failed(_) => false,
1073 }
1074 }
1075
1076 pub fn is_in_multi_statement_transaction(&self) -> bool {
1078 match self {
1079 TransactionStatus::InTransaction(_) | TransactionStatus::InTransactionImplicit(_) => {
1080 true
1081 }
1082 TransactionStatus::Default
1083 | TransactionStatus::Started(_)
1084 | TransactionStatus::Failed(_) => false,
1085 }
1086 }
1087
1088 pub fn in_immediate_multi_stmt_txn(&self, when: &QueryWhen) -> bool {
1090 self.is_in_multi_statement_transaction() && when == &QueryWhen::Immediately
1091 }
1092
1093 pub fn try_grant_write_locks(&mut self, guards: WriteLocks) -> Result<(), &WriteLocks> {
1102 match self {
1103 TransactionStatus::Default => panic!("cannot grant write lock to txn not yet started"),
1104 TransactionStatus::Started(txn)
1105 | TransactionStatus::InTransaction(txn)
1106 | TransactionStatus::InTransactionImplicit(txn)
1107 | TransactionStatus::Failed(txn) => txn.try_grant_write_locks(guards),
1108 }
1109 }
1110
1111 pub fn write_locks(&self) -> Option<&WriteLocks> {
1113 match self {
1114 TransactionStatus::Default => None,
1115 TransactionStatus::Started(txn)
1116 | TransactionStatus::InTransaction(txn)
1117 | TransactionStatus::InTransactionImplicit(txn)
1118 | TransactionStatus::Failed(txn) => txn.write_lock_guards.as_ref(),
1119 }
1120 }
1121
1122 pub fn timeline(&self) -> Option<Timeline> {
1124 match self {
1125 TransactionStatus::Default => None,
1126 TransactionStatus::Started(txn)
1127 | TransactionStatus::InTransaction(txn)
1128 | TransactionStatus::InTransactionImplicit(txn)
1129 | TransactionStatus::Failed(txn) => txn.timeline(),
1130 }
1131 }
1132
1133 pub fn cluster(&self) -> Option<ClusterId> {
1135 match self {
1136 TransactionStatus::Default => None,
1137 TransactionStatus::Started(txn)
1138 | TransactionStatus::InTransaction(txn)
1139 | TransactionStatus::InTransactionImplicit(txn)
1140 | TransactionStatus::Failed(txn) => txn.cluster(),
1141 }
1142 }
1143
1144 pub fn catalog_state(&self) -> Option<&CatalogState> {
1146 match self.inner() {
1147 Some(Transaction {
1148 ops: TransactionOps::DDL { state, .. },
1149 ..
1150 }) => Some(state),
1151 _ => None,
1152 }
1153 }
1154
1155 pub fn contains_ops(&self) -> bool {
1157 match self.inner() {
1158 Some(txn) => txn.contains_ops(),
1159 None => false,
1160 }
1161 }
1162
1163 pub fn add_ops(&mut self, add_ops: TransactionOps<T>) -> Result<(), AdapterError> {
1176 match self {
1177 TransactionStatus::Started(Transaction { ops, access, .. })
1178 | TransactionStatus::InTransaction(Transaction { ops, access, .. })
1179 | TransactionStatus::InTransactionImplicit(Transaction { ops, access, .. }) => {
1180 match ops {
1181 TransactionOps::None => {
1182 if matches!(access, Some(TransactionAccessMode::ReadOnly))
1183 && matches!(add_ops, TransactionOps::Writes(_))
1184 {
1185 return Err(AdapterError::ReadOnlyTransaction);
1186 }
1187 *ops = add_ops;
1188 }
1189 TransactionOps::Peeks {
1190 determination,
1191 cluster_id,
1192 requires_linearization,
1193 } => match add_ops {
1194 TransactionOps::Peeks {
1195 determination: add_timestamp_determination,
1196 cluster_id: add_cluster_id,
1197 requires_linearization: add_requires_linearization,
1198 } => {
1199 assert_eq!(*cluster_id, add_cluster_id);
1200 match (
1201 &determination.timestamp_context,
1202 &add_timestamp_determination.timestamp_context,
1203 ) {
1204 (
1205 TimestampContext::TimelineTimestamp {
1206 timeline: txn_timeline,
1207 chosen_ts: txn_ts,
1208 oracle_ts: _,
1209 },
1210 TimestampContext::TimelineTimestamp {
1211 timeline: add_timeline,
1212 chosen_ts: add_ts,
1213 oracle_ts: _,
1214 },
1215 ) => {
1216 assert_eq!(txn_timeline, add_timeline);
1217 assert_eq!(txn_ts, add_ts);
1218 }
1219 (TimestampContext::NoTimestamp, _) => {
1220 *determination = add_timestamp_determination
1221 }
1222 (_, TimestampContext::NoTimestamp) => {}
1223 };
1224 if matches!(requires_linearization, RequireLinearization::NotRequired)
1225 && matches!(
1226 add_requires_linearization,
1227 RequireLinearization::Required
1228 )
1229 {
1230 *requires_linearization = add_requires_linearization;
1231 }
1232 }
1233 writes @ TransactionOps::Writes(..)
1237 if !determination.timestamp_context.contains_timestamp() =>
1238 {
1239 *ops = writes;
1240 }
1241 _ => return Err(AdapterError::ReadOnlyTransaction),
1242 },
1243 TransactionOps::Subscribe => {
1244 return Err(AdapterError::SubscribeOnlyTransaction);
1245 }
1246 TransactionOps::Writes(txn_writes) => match add_ops {
1247 TransactionOps::Writes(mut add_writes) => {
1248 assert!(!matches!(access, Some(TransactionAccessMode::ReadOnly)));
1251 txn_writes.append(&mut add_writes);
1252 }
1253 TransactionOps::Peeks { determination, .. }
1256 if !determination.timestamp_context.contains_timestamp() => {}
1257 _ => {
1258 return Err(AdapterError::WriteOnlyTransaction);
1259 }
1260 },
1261 TransactionOps::SingleStatement { .. } => {
1262 return Err(AdapterError::SingleStatementTransaction);
1263 }
1264 TransactionOps::DDL {
1265 ops: og_ops,
1266 revision: og_revision,
1267 state: og_state,
1268 } => match add_ops {
1269 TransactionOps::DDL {
1270 ops: new_ops,
1271 revision: new_revision,
1272 state: new_state,
1273 } => {
1274 if *og_revision != new_revision {
1275 return Err(AdapterError::DDLTransactionRace);
1276 }
1277 if !new_ops.is_empty() {
1279 *og_ops = new_ops;
1280 *og_state = new_state;
1281 }
1282 }
1283 _ => return Err(AdapterError::DDLOnlyTransaction),
1284 },
1285 }
1286 }
1287 TransactionStatus::Default | TransactionStatus::Failed(_) => {
1288 unreachable!()
1289 }
1290 }
1291 Ok(())
1292 }
1293}
1294
1295pub type TransactionId = u64;
1297
1298impl<T> Default for TransactionStatus<T> {
1299 fn default() -> Self {
1300 TransactionStatus::Default
1301 }
1302}
1303
1304#[derive(Debug)]
1306pub struct Transaction<T> {
1307 pub pcx: PlanContext,
1309 pub ops: TransactionOps<T>,
1311 pub id: TransactionId,
1316 write_lock_guards: Option<WriteLocks>,
1318 access: Option<TransactionAccessMode>,
1320}
1321
1322impl<T> Transaction<T> {
1323 fn try_grant_write_locks(&mut self, guards: WriteLocks) -> Result<(), &WriteLocks> {
1326 match &mut self.write_lock_guards {
1327 Some(existing) => Err(existing),
1328 locks @ None => {
1329 *locks = Some(guards);
1330 Ok(())
1331 }
1332 }
1333 }
1334
1335 fn timeline(&self) -> Option<Timeline> {
1337 match &self.ops {
1338 TransactionOps::Peeks {
1339 determination:
1340 TimestampDetermination {
1341 timestamp_context: TimestampContext::TimelineTimestamp { timeline, .. },
1342 ..
1343 },
1344 ..
1345 } => Some(timeline.clone()),
1346 TransactionOps::Peeks { .. }
1347 | TransactionOps::None
1348 | TransactionOps::Subscribe
1349 | TransactionOps::Writes(_)
1350 | TransactionOps::SingleStatement { .. }
1351 | TransactionOps::DDL { .. } => None,
1352 }
1353 }
1354
1355 pub fn cluster(&self) -> Option<ClusterId> {
1357 match &self.ops {
1358 TransactionOps::Peeks { cluster_id, .. } => Some(cluster_id.clone()),
1359 TransactionOps::None
1360 | TransactionOps::Subscribe
1361 | TransactionOps::Writes(_)
1362 | TransactionOps::SingleStatement { .. }
1363 | TransactionOps::DDL { .. } => None,
1364 }
1365 }
1366
1367 fn contains_ops(&self) -> bool {
1369 !matches!(self.ops, TransactionOps::None)
1370 }
1371}
1372
1373#[derive(Debug, Clone, Copy)]
1375pub enum TransactionCode {
1376 Idle,
1378 InTransaction,
1380 Failed,
1382}
1383
1384impl From<TransactionCode> for u8 {
1385 fn from(code: TransactionCode) -> Self {
1386 match code {
1387 TransactionCode::Idle => b'I',
1388 TransactionCode::InTransaction => b'T',
1389 TransactionCode::Failed => b'E',
1390 }
1391 }
1392}
1393
1394impl From<TransactionCode> for String {
1395 fn from(code: TransactionCode) -> Self {
1396 char::from(u8::from(code)).to_string()
1397 }
1398}
1399
1400impl<T> From<&TransactionStatus<T>> for TransactionCode {
1401 fn from(status: &TransactionStatus<T>) -> TransactionCode {
1403 match status {
1404 TransactionStatus::Default => TransactionCode::Idle,
1405 TransactionStatus::Started(_) => TransactionCode::InTransaction,
1406 TransactionStatus::InTransaction(_) => TransactionCode::InTransaction,
1407 TransactionStatus::InTransactionImplicit(_) => TransactionCode::InTransaction,
1408 TransactionStatus::Failed(_) => TransactionCode::Failed,
1409 }
1410 }
1411}
1412
1413#[derive(Debug)]
1419pub enum TransactionOps<T> {
1420 None,
1423 Peeks {
1428 determination: TimestampDetermination<T>,
1430 cluster_id: ClusterId,
1432 requires_linearization: RequireLinearization,
1434 },
1435 Subscribe,
1437 Writes(Vec<WriteOp>),
1440 SingleStatement {
1442 stmt: Arc<Statement<Raw>>,
1444 params: mz_sql::plan::Params,
1446 },
1447 DDL {
1451 ops: Vec<crate::catalog::Op>,
1453 state: CatalogState,
1455 revision: u64,
1457 },
1458}
1459
1460impl<T> TransactionOps<T> {
1461 fn timestamp_determination(self) -> Option<TimestampDetermination<T>> {
1462 match self {
1463 TransactionOps::Peeks { determination, .. } => Some(determination),
1464 TransactionOps::None
1465 | TransactionOps::Subscribe
1466 | TransactionOps::Writes(_)
1467 | TransactionOps::SingleStatement { .. }
1468 | TransactionOps::DDL { .. } => None,
1469 }
1470 }
1471}
1472
1473impl<T> Default for TransactionOps<T> {
1474 fn default() -> Self {
1475 Self::None
1476 }
1477}
1478
1479#[derive(Debug, Clone, PartialEq)]
1481pub struct WriteOp {
1482 pub id: CatalogItemId,
1484 pub rows: TableData,
1486}
1487
1488#[derive(Debug)]
1490pub enum RequireLinearization {
1491 Required,
1493 NotRequired,
1495}
1496
1497impl From<&ExplainContext> for RequireLinearization {
1498 fn from(ctx: &ExplainContext) -> Self {
1499 match ctx {
1500 ExplainContext::None | ExplainContext::PlanInsightsNotice(_) => {
1501 RequireLinearization::Required
1502 }
1503 _ => RequireLinearization::NotRequired,
1504 }
1505 }
1506}
1507
1508#[derive(Debug)]
1512pub struct WriteLocks {
1513 locks: BTreeMap<CatalogItemId, tokio::sync::OwnedMutexGuard<()>>,
1514 conn_id: ConnectionId,
1516}
1517
1518impl WriteLocks {
1519 pub fn builder(sources: impl IntoIterator<Item = CatalogItemId>) -> WriteLocksBuilder {
1524 let locks = sources.into_iter().map(|gid| (gid, None)).collect();
1525 WriteLocksBuilder { locks }
1526 }
1527
1528 pub fn validate(
1531 self,
1532 collections: impl Iterator<Item = CatalogItemId>,
1533 ) -> Result<Self, BTreeSet<CatalogItemId>> {
1534 let mut missing = BTreeSet::new();
1535 for collection in collections {
1536 if !self.locks.contains_key(&collection) {
1537 missing.insert(collection);
1538 }
1539 }
1540
1541 if missing.is_empty() {
1542 Ok(self)
1543 } else {
1544 drop(self);
1546 Err(missing)
1547 }
1548 }
1549}
1550
1551impl Drop for WriteLocks {
1552 fn drop(&mut self) {
1553 if !self.locks.is_empty() {
1555 tracing::info!(
1556 conn_id = %self.conn_id,
1557 locks = ?self.locks,
1558 "dropping write locks",
1559 );
1560 }
1561 }
1562}
1563
1564#[derive(Debug)]
1568pub struct WriteLocksBuilder {
1569 locks: BTreeMap<CatalogItemId, Option<tokio::sync::OwnedMutexGuard<()>>>,
1570}
1571
1572impl WriteLocksBuilder {
1573 pub fn insert_lock(&mut self, id: CatalogItemId, lock: tokio::sync::OwnedMutexGuard<()>) {
1575 self.locks.insert(id, Some(lock));
1576 }
1577
1578 pub fn all_or_nothing(self, conn_id: &ConnectionId) -> Result<WriteLocks, CatalogItemId> {
1583 let (locks, missing): (BTreeMap<_, _>, BTreeSet<_>) =
1584 self.locks
1585 .into_iter()
1586 .partition_map(|(gid, lock)| match lock {
1587 Some(lock) => itertools::Either::Left((gid, lock)),
1588 None => itertools::Either::Right(gid),
1589 });
1590
1591 match missing.iter().next() {
1592 None => {
1593 tracing::info!(%conn_id, ?locks, "acquired write locks");
1594 Ok(WriteLocks {
1595 locks,
1596 conn_id: conn_id.clone(),
1597 })
1598 }
1599 Some(gid) => {
1600 tracing::info!(?missing, "failed to acquire write locks");
1601 drop(locks);
1603 Err(*gid)
1604 }
1605 }
1606 }
1607}
1608
1609#[derive(Debug, Default)]
1658pub(crate) struct GroupCommitWriteLocks {
1659 locks: BTreeMap<CatalogItemId, tokio::sync::OwnedMutexGuard<()>>,
1660}
1661
1662impl GroupCommitWriteLocks {
1663 pub fn merge(&mut self, mut locks: WriteLocks) {
1665 let existing = std::mem::take(&mut locks.locks);
1669 self.locks.extend(existing);
1670 }
1671
1672 pub fn missing_locks(
1674 &self,
1675 writes: impl Iterator<Item = CatalogItemId>,
1676 ) -> BTreeSet<CatalogItemId> {
1677 let mut missing = BTreeSet::new();
1678 for write in writes {
1679 if !self.locks.contains_key(&write) {
1680 missing.insert(write);
1681 }
1682 }
1683 missing
1684 }
1685}
1686
1687impl Drop for GroupCommitWriteLocks {
1688 fn drop(&mut self) {
1689 if !self.locks.is_empty() {
1690 tracing::info!(
1691 locks = ?self.locks,
1692 "dropping group commit write locks",
1693 );
1694 }
1695 }
1696}