mz_adapter/
session.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Per-connection configuration parameters and state.
11
12#![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/// A session holds per-connection state.
69#[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    /// A globally unique identifier for the session. Not to be confused
77    /// with `conn_id`, which may be reused.
78    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    /// The role metadata of the current session.
88    ///
89    /// Invariant: role_metadata must be `Some` after the user has
90    /// successfully connected to and authenticated with Materialize.
91    ///
92    /// Prefer using this value over [`Self.user.name`].
93    //
94    // It would be better for this not to be an Option, but the
95    // `Session` is initialized before the user has connected to
96    // Materialize and is able to look up the `RoleMetadata`. The `Session`
97    // is also used to return an error when no role exists and
98    // therefore there is no valid `RoleMetadata`.
99    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    // Token allowing us to access `Arc<QCell<StatementLogging>>`
108    // metadata. We want these to be reference-counted, because the same
109    // statement might be referenced from multiple portals simultaneously.
110    //
111    // However, they can't be `Rc<RefCell<StatementLogging>>`, because
112    // the `Session` is sent around to different threads.
113    //
114    // On the other hand, they don't need to be
115    // `Arc<Mutex<StatementLogging>>`, because they will always be
116    // accessed from the same thread that the `Session` is currently
117    // on. We express this by gating access with this token.
118    #[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/// Data structure suitable for passing to other threads that need access to some common Session
156/// properties.
157#[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/// Configures a new [`Session`].
189#[derive(Debug, Clone)]
190pub struct SessionConfig {
191    /// The connection ID for the session.
192    ///
193    /// May be reused after the session terminates.
194    pub conn_id: ConnectionId,
195    /// A universally unique identifier for the session, across all processes,
196    /// region, and all time.
197    ///
198    /// Must not be reused, even after the session terminates.
199    pub uuid: Uuid,
200    /// The peer address of the client
201    pub client_ip: Option<IpAddr>,
202    /// The name of the user associated with the session.
203    pub user: String,
204    /// An optional receiver that the session will periodically check for
205    /// updates to a user's external metadata.
206    pub external_metadata_rx: Option<watch::Receiver<ExternalUserMetadata>>,
207    /// The metadata of the user associated with the session.
208    pub internal_user_metadata: Option<InternalUserMetadata>,
209    /// Helm chart version
210    pub helm_chart_version: Option<String>,
211}
212
213impl<T: TimestampManipulation> Session<T> {
214    /// Creates a new session for the specified connection ID.
215    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    /// Returns a reference-less collection of data usable by other tasks that don't have ownership
225    /// of the Session.
226    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        // TODO: soft_assert that these are the same as Session.
236    }
237
238    /// Creates new statement logging metadata for a one-off
239    /// statement.
240    // Normally, such logging information would be created as part of
241    // allocating a new prepared statement, and a refcounted handle
242    // would be copied from that prepared statement to portals during
243    // binding. However, we also support (via `Command::declare`)
244    // binding a statement directly to a portal without creating an
245    // intermediate prepared statement. Thus, for those cases, a
246    // mechanism for generating the logging metadata directly is needed.
247    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    /// Returns a unique ID for the session.
271    /// Not to be confused with `connection_id`, which can be reused.
272    pub fn uuid(&self) -> Uuid {
273        self.uuid
274    }
275
276    /// Creates a new dummy session.
277    ///
278    /// Dummy sessions are intended for use when executing queries on behalf of
279    /// the system itself, rather than on behalf of a user.
280    pub fn dummy() -> Session<T> {
281        let registry = MetricsRegistry::new();
282        let metrics = Metrics::register_into(&registry);
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    /// Returns the secret key associated with the session.
350    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    /// Starts an explicit transaction, or changes an implicit to an explicit
362    /// transaction.
363    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        // Check that current transaction state is compatible with new `access`
370        if let Some(txn) = self.transaction.inner() {
371            // `READ WRITE` prohibited if:
372            // - Currently in `READ ONLY`
373            // - Already performed a query
374            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    /// Starts either a single statement or implicit transaction based on the
421    /// number of statements, but only if no transaction has been started already.
422    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    /// Starts a single statement transaction, but only if no transaction has been started already.
442    pub fn start_transaction_single_stmt(&mut self, wall_time: DateTime<Utc>) {
443        self.start_transaction_implicit(wall_time, 1);
444    }
445
446    /// Clears a transaction, setting its state to Default and destroying all
447    /// portals. Returned are:
448    /// - sinks that were started in this transaction and need to be dropped
449    /// - the cleared transaction so its operations can be handled
450    ///
451    /// The [Postgres protocol docs](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) specify:
452    /// > a named portal object lasts till the end of the current transaction
453    /// and
454    /// > An unnamed portal is destroyed at the end of the transaction
455    #[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    /// Marks the current transaction as failed.
463    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    /// Returns the current transaction status.
477    pub fn transaction(&self) -> &TransactionStatus<T> {
478        &self.transaction
479    }
480
481    /// Returns the current transaction status.
482    pub fn transaction_mut(&mut self) -> &mut TransactionStatus<T> {
483        &mut self.transaction
484    }
485
486    /// Returns the session's transaction code.
487    pub fn transaction_code(&self) -> TransactionCode {
488        self.transaction().into()
489    }
490
491    /// Adds operations to the current transaction. An error is produced if
492    /// they cannot be merged (i.e., a timestamp-dependent read cannot be
493    /// merged to an insert).
494    pub fn add_transaction_ops(&mut self, add_ops: TransactionOps<T>) -> Result<(), AdapterError> {
495        self.transaction.add_ops(add_ops)
496    }
497
498    /// Returns a channel on which to send notices to the session.
499    pub fn retain_notice_transmitter(&self) -> UnboundedSender<AdapterNotice> {
500        self.notices_tx.clone()
501    }
502
503    /// Adds a notice to the session.
504    pub fn add_notice(&self, notice: AdapterNotice) {
505        self.add_notices([notice])
506    }
507
508    /// Adds multiple notices to the session.
509    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    /// Awaits a possible notice.
516    ///
517    /// This method is cancel safe.
518    pub async fn recv_notice(&mut self) -> AdapterNotice {
519        // This method is cancel safe because recv is cancel safe.
520        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    /// Returns a draining iterator over the notices attached to the session.
534    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    /// Returns Some if the notice should be reported, otherwise None.
545    fn notice_filter(&self, notice: AdapterNotice) -> Option<AdapterNotice> {
546        // Filter out low threshold severity.
547        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        // Filter out notices for other clusters.
553        if let AdapterNotice::ClusterReplicaStatusChanged { cluster, .. } = &notice {
554            if cluster != self.vars.cluster() {
555                return None;
556            }
557        }
558        Some(notice)
559    }
560
561    /// Sets the transaction ops to `TransactionOps::None`. Must only be used after
562    /// verifying that no transaction anomalies will occur if cleared.
563    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    /// If the current transaction ops belong to a read, then sets the
570    /// ops to `None`, returning the old read timestamp context if
571    /// any existed. Must only be used after verifying that no transaction
572    /// anomalies will occur if cleared.
573    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    /// Returns the transaction's read timestamp determination, if set.
591    ///
592    /// Returns `None` if there is no active transaction, or if the active
593    /// transaction is not a read transaction.
594    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    /// Whether this session has a timestamp for a read transaction.
608    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    /// Registers the prepared statement under `name`.
628    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    /// Removes the prepared statement associated with `name`.
655    ///
656    /// Returns whether a statement previously existed.
657    pub fn remove_prepared_statement(&mut self, name: &str) -> bool {
658        self.prepared_statements.remove(name).is_some()
659    }
660
661    /// Removes all prepared statements.
662    pub fn remove_all_prepared_statements(&mut self) {
663        self.prepared_statements.clear();
664    }
665
666    /// Retrieves the prepared statement associated with `name`.
667    ///
668    /// This is unverified and could be incorrect if the underlying catalog has
669    /// changed.
670    pub fn get_prepared_statement_unverified(&self, name: &str) -> Option<&PreparedStatement> {
671        self.prepared_statements.get(name)
672    }
673
674    /// Retrieves the prepared statement associated with `name`.
675    ///
676    /// This is unverified and could be incorrect if the underlying catalog has
677    /// changed.
678    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    /// Returns the prepared statements for the session.
686    pub fn prepared_statements(&self) -> &BTreeMap<String, PreparedStatement> {
687        &self.prepared_statements
688    }
689
690    /// Binds the specified portal to the specified prepared statement.
691    ///
692    /// If the prepared statement contains parameters, the values and types of
693    /// those parameters must be provided in `params`. It is the caller's
694    /// responsibility to ensure that the correct number of parameters is
695    /// provided.
696    ///
697    /// The `results_formats` parameter sets the desired format of the results,
698    /// and is stored on the portal.
699    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        // The empty portal can be silently replaced.
710        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    /// Removes the specified portal.
732    ///
733    /// If there is no such portal, this method does nothing. Returns whether that portal existed.
734    pub fn remove_portal(&mut self, portal_name: &str) -> bool {
735        self.portals.remove(portal_name).is_some()
736    }
737
738    /// Retrieves a reference to the specified portal.
739    ///
740    /// If there is no such portal, returns `None`.
741    pub fn get_portal_unverified(&self, portal_name: &str) -> Option<&Portal> {
742        self.portals.get(portal_name)
743    }
744
745    /// Retrieves a mutable reference to the specified portal.
746    ///
747    /// If there is no such portal, returns `None`.
748    pub fn get_portal_unverified_mut(&mut self, portal_name: &str) -> Option<&mut Portal> {
749        self.portals.get_mut(portal_name)
750    }
751
752    /// Creates and installs a new portal.
753    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        // See: https://github.com/postgres/postgres/blob/84f5c2908dad81e8622b0406beea580e40bb03ac/src/backend/utils/mmgr/portalmem.c#L234
763
764        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    /// Resets the session to its initial state. Returns sinks that need to be
787    /// dropped.
788    pub fn reset(&mut self) {
789        let _ = self.clear_transaction();
790        self.prepared_statements.clear();
791        self.vars.reset_all();
792    }
793
794    /// Returns the [application_name] that created this session.
795    ///
796    /// [application_name]: (https://www.postgresql.org/docs/current/runtime-config-logging.html#GUC-APPLICATION-NAME)
797    pub fn application_name(&self) -> &str {
798        self.vars.application_name()
799    }
800
801    /// Returns a reference to the variables in this session.
802    pub fn vars(&self) -> &SessionVars {
803        &self.vars
804    }
805
806    /// Returns a mutable reference to the variables in this session.
807    pub fn vars_mut(&mut self) -> &mut SessionVars {
808        &mut self.vars
809    }
810
811    /// Grants a set of write locks to this session's inner [`Transaction`].
812    ///
813    /// # Panics
814    /// If the inner transaction is idle. See [`TransactionStatus::try_grant_write_locks`].
815    ///
816    pub fn try_grant_write_locks(&mut self, guards: WriteLocks) -> Result<(), &WriteLocks> {
817        self.transaction.try_grant_write_locks(guards)
818    }
819
820    /// Drains any external metadata updates and applies the changes from the latest update.
821    pub fn apply_external_metadata_updates(&mut self) {
822        // If no sender is registered then there isn't anything to do.
823        let Some(rx) = &mut self.external_metadata_rx else {
824            return;
825        };
826
827        // If the value hasn't changed then return.
828        if !rx.has_changed().unwrap_or(false) {
829            return;
830        }
831
832        // Update our metadata! Note the short critical section (just a clone) to avoid blocking
833        // the sending side of this watch channel.
834        let metadata = rx.borrow_and_update().clone();
835        self.vars.set_external_user_metadata(metadata);
836    }
837
838    /// Initializes the session's role metadata.
839    pub fn initialize_role_metadata(&mut self, role_id: RoleId) {
840        self.role_metadata = Some(RoleMetadata::new(role_id));
841    }
842
843    /// Ensures that a timestamp oracle exists for `timeline` and returns a mutable reference to
844    /// the timestamp oracle.
845    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    /// Ensures that a timestamp oracle exists for reads and writes from/to a local input and
855    /// returns a mutable reference to the timestamp oracle.
856    pub fn ensure_local_timestamp_oracle(&mut self) -> &mut InMemoryTimestampOracle<T, NowFn<T>> {
857        self.ensure_timestamp_oracle(Timeline::EpochMilliseconds)
858    }
859
860    /// Returns a reference to the timestamp oracle for `timeline`.
861    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    /// If the current session is using the Strong Session Serializable isolation level advance the
869    /// session local timestamp oracle to `write_ts`.
870    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    /// Returns the [`SessionMetrics`] instance associated with this [`Session`].
877    pub fn metrics(&self) -> &SessionMetrics {
878        &self.metrics
879    }
880
881    /// Sets the `BuiltinTableAppendNotify` for this session.
882    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    /// Takes the stashed `BuiltinTableAppendNotify`, if one exists, and returns a [`Future`] that
888    /// waits for the writes to complete.
889    pub fn clear_builtin_table_updates(&mut self) -> Option<impl Future<Output = ()> + 'static> {
890        if let Some(fut) = self.builtin_updates.take() {
891            // Record how long we blocked for, if we blocked at all.
892            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/// A prepared statement.
906#[derive(Derivative, Clone)]
907#[derivative(Debug)]
908pub struct PreparedStatement {
909    stmt: Option<Statement<Raw>>,
910    desc: StatementDesc,
911    /// The most recent catalog revision that has verified this statement.
912    pub catalog_revision: u64,
913    #[derivative(Debug = "ignore")]
914    logging: Arc<QCell<PreparedStatementLoggingInfo>>,
915}
916
917impl PreparedStatement {
918    /// Returns the AST associated with this prepared statement,
919    /// if the prepared statement was not the empty query.
920    pub fn stmt(&self) -> Option<&Statement<Raw>> {
921        self.stmt.as_ref()
922    }
923
924    /// Returns the description of the prepared statement.
925    pub fn desc(&self) -> &StatementDesc {
926        &self.desc
927    }
928
929    /// Returns a handle to the metadata for statement logging.
930    pub fn logging(&self) -> &Arc<QCell<PreparedStatementLoggingInfo>> {
931        &self.logging
932    }
933}
934
935/// A portal represents the execution state of a running or runnable query.
936#[derive(Derivative)]
937#[derivative(Debug)]
938pub struct Portal {
939    /// The statement that is bound to this portal.
940    pub stmt: Option<Arc<Statement<Raw>>>,
941    /// The statement description.
942    pub desc: StatementDesc,
943    /// The most recent catalog revision that has verified this statement.
944    pub catalog_revision: u64,
945    /// The bound values for the parameters in the prepared statement, if any.
946    pub parameters: Params,
947    /// The desired output format for each column in the result set.
948    pub result_formats: Vec<Format>,
949    /// A handle to metadata needed for statement logging.
950    #[derivative(Debug = "ignore")]
951    pub logging: Arc<QCell<PreparedStatementLoggingInfo>>,
952    /// The execution state of the portal.
953    #[derivative(Debug = "ignore")]
954    pub state: PortalState,
955}
956
957/// Execution states of a portal.
958pub enum PortalState {
959    /// Portal not yet started.
960    NotStarted,
961    /// Portal is a rows-returning statement in progress with 0 or more rows
962    /// remaining.
963    InProgress(Option<InProgressRows>),
964    /// Portal has completed and should not be re-executed. If the optional string
965    /// is present, it is returned as a CommandComplete tag, otherwise an error
966    /// is sent.
967    Completed(Option<String>),
968}
969
970/// State of an in-progress, rows-returning portal.
971pub struct InProgressRows {
972    /// The current batch of rows.
973    pub current: Option<Box<dyn RowIterator + Send + Sync>>,
974    /// A stream from which to fetch more row batches.
975    pub remaining: RecordFirstRowStream,
976}
977
978impl InProgressRows {
979    /// Creates a new InProgressRows from a batch stream.
980    pub fn new(remaining: RecordFirstRowStream) -> Self {
981        Self {
982            current: None,
983            remaining,
984        }
985    }
986}
987
988/// A channel of batched rows.
989pub type RowBatchStream = UnboundedReceiver<PeekResponseUnary>;
990
991/// The transaction status of a session.
992///
993/// PostgreSQL's transaction states are in backend/access/transam/xact.c.
994#[derive(Debug)]
995pub enum TransactionStatus<T> {
996    /// Idle. Matches `TBLOCK_DEFAULT`.
997    Default,
998    /// Running a single-query transaction. Matches
999    /// `TBLOCK_STARTED`. In PostgreSQL, when using the extended query protocol, this
1000    /// may be upgraded into multi-statement implicit query (see [`Self::InTransactionImplicit`]).
1001    /// Additionally, some statements may trigger an eager commit of the implicit transaction,
1002    /// see: <https://git.postgresql.org/gitweb/?p=postgresql.git&a=commitdiff&h=f92944137>. In
1003    /// Materialize however, we eagerly commit all statements outside of an explicit transaction
1004    /// when using the extended query protocol. Therefore, we can guarantee that this state will
1005    /// always be a single-query transaction and never be upgraded into a multi-statement implicit
1006    /// query.
1007    Started(Transaction<T>),
1008    /// Currently in a transaction issued from a `BEGIN`. Matches `TBLOCK_INPROGRESS`.
1009    InTransaction(Transaction<T>),
1010    /// Currently in an implicit transaction started from a multi-statement query
1011    /// with more than 1 statements. Matches `TBLOCK_IMPLICIT_INPROGRESS`.
1012    InTransactionImplicit(Transaction<T>),
1013    /// In a failed transaction. Matches `TBLOCK_ABORT`.
1014    Failed(Transaction<T>),
1015}
1016
1017impl<T: TimestampManipulation> TransactionStatus<T> {
1018    /// Extracts the inner transaction ops and write lock guard if not failed.
1019    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    /// Exposes the inner transaction.
1031    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    /// Exposes the inner transaction.
1042    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    /// Whether the transaction's ops are DDL.
1053    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    /// Expresses whether or not the transaction was implicitly started.
1066    /// However, its negation does not imply explicitly started.
1067    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    /// Whether the transaction may contain multiple statements.
1077    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    /// Whether the transaction is in a multi-statement, immediate transaction.
1089    pub fn in_immediate_multi_stmt_txn(&self, when: &QueryWhen) -> bool {
1090        self.is_in_multi_statement_transaction() && when == &QueryWhen::Immediately
1091    }
1092
1093    /// Grants the writes lock to the inner transaction, returning an error if the transaction
1094    /// has already been granted write locks.
1095    ///
1096    /// # Panics
1097    /// If `self` is `TransactionStatus::Default`, which indicates that the
1098    /// transaction is idle, which is not appropriate to assign the
1099    /// coordinator's write lock to.
1100    ///
1101    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    /// Returns the currently held [`WriteLocks`], if this transaction holds any.
1112    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    /// The timeline of the transaction, if one exists.
1123    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    /// The cluster of the transaction, if one exists.
1134    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    /// Snapshot of the catalog that reflects DDL operations run in this transaction.
1145    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    /// Reports whether any operations have been executed as part of this transaction
1156    pub fn contains_ops(&self) -> bool {
1157        match self.inner() {
1158            Some(txn) => txn.contains_ops(),
1159            None => false,
1160        }
1161    }
1162
1163    /// Adds operations to the current transaction. An error is produced if they cannot be merged
1164    /// (i.e., a timestamp-dependent read cannot be merged to an insert).
1165    ///
1166    /// The `DDL` variant is an exception and does not merge operations, but instead overwrites the
1167    /// old ops with the new ops. This is correct because it is only used in conjunction with the
1168    /// Dry Run catalog op which returns an error containing all of the ops, and those ops are
1169    /// passed to this function which then overwrites.
1170    ///
1171    /// # Panics
1172    /// If the operations are compatible but the operation metadata doesn't match. Such as reads at
1173    /// different timestamps, reads on different timelines, reads on different clusters, etc. It's
1174    /// up to the caller to make sure these are aligned.
1175    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                        // Iff peeks thus far do not have a timestamp (i.e.
1234                        // they are constant), we can switch to a write
1235                        // transaction.
1236                        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                            // We should have already checked the access above, but make sure we don't miss
1249                            // it anyway.
1250                            assert!(!matches!(access, Some(TransactionAccessMode::ReadOnly)));
1251                            txn_writes.append(&mut add_writes);
1252                        }
1253                        // Iff peeks do not have a timestamp (i.e. they are
1254                        // constant), we can permit them.
1255                        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                            // The old og_ops are overwritten, not extended.
1278                            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
1295/// An abstraction allowing us to identify different transactions.
1296pub type TransactionId = u64;
1297
1298impl<T> Default for TransactionStatus<T> {
1299    fn default() -> Self {
1300        TransactionStatus::Default
1301    }
1302}
1303
1304/// State data for transactions.
1305#[derive(Debug)]
1306pub struct Transaction<T> {
1307    /// Plan context.
1308    pub pcx: PlanContext,
1309    /// Transaction operations.
1310    pub ops: TransactionOps<T>,
1311    /// Uniquely identifies the transaction on a per connection basis.
1312    /// Two transactions started from separate connections may share the
1313    /// same ID.
1314    /// If all IDs have been exhausted, this will wrap around back to 0.
1315    pub id: TransactionId,
1316    /// Locks for objects this transaction will operate on.
1317    write_lock_guards: Option<WriteLocks>,
1318    /// Access mode (read only, read write).
1319    access: Option<TransactionAccessMode>,
1320}
1321
1322impl<T> Transaction<T> {
1323    /// Tries to grant the write lock to this transaction for the remainder of its lifetime. Errors
1324    /// if this [`Transaction`] has already been granted write locks.
1325    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    /// The timeline of the transaction, if one exists.
1336    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    /// The cluster of the transaction, if one exists.
1356    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    /// Reports whether any operations have been executed as part of this transaction
1368    fn contains_ops(&self) -> bool {
1369        !matches!(self.ops, TransactionOps::None)
1370    }
1371}
1372
1373/// A transaction's status code.
1374#[derive(Debug, Clone, Copy)]
1375pub enum TransactionCode {
1376    /// Not currently in a transaction
1377    Idle,
1378    /// Currently in a transaction
1379    InTransaction,
1380    /// Currently in a transaction block which is failed
1381    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    /// Convert from the Session's version
1402    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/// The type of operation being performed by the transaction.
1414///
1415/// This is needed because we currently do not allow mixing reads and writes in
1416/// a transaction. Use this to record what we have done, and what may need to
1417/// happen at commit.
1418#[derive(Debug)]
1419pub enum TransactionOps<T> {
1420    /// The transaction has been initiated, but no statement has yet been executed
1421    /// in it.
1422    None,
1423    /// This transaction has had a peek (`SELECT`, `SUBSCRIBE`). If the inner value
1424    /// is has a timestamp, it must only do other peeks. However, if it doesn't
1425    /// have a timestamp (i.e. the values are constants), the transaction can still
1426    /// perform writes.
1427    Peeks {
1428        /// The timestamp and timestamp related metadata for the peek.
1429        determination: TimestampDetermination<T>,
1430        /// The cluster used to execute peeks.
1431        cluster_id: ClusterId,
1432        /// Whether this peek needs to be linearized.
1433        requires_linearization: RequireLinearization,
1434    },
1435    /// This transaction has done a `SUBSCRIBE` and must do nothing else.
1436    Subscribe,
1437    /// This transaction has had a write (`INSERT`, `UPDATE`, `DELETE`) and must
1438    /// only do other writes, or reads whose timestamp is None (i.e. constants).
1439    Writes(Vec<WriteOp>),
1440    /// This transaction has a prospective statement that will execute during commit.
1441    SingleStatement {
1442        /// The prospective statement.
1443        stmt: Arc<Statement<Raw>>,
1444        /// The statement params.
1445        params: mz_sql::plan::Params,
1446    },
1447    /// This transaction has run some _simple_ DDL and must do nothing else. Any statement/plan that
1448    /// uses this must return false in `must_serialize_ddl()` because this is serialized instead in
1449    /// `sequence_plan()` during `COMMIT`.
1450    DDL {
1451        /// Catalog operations that have already run, and must run before each subsequent op.
1452        ops: Vec<crate::catalog::Op>,
1453        /// In-memory state that reflects the previously applied ops.
1454        state: CatalogState,
1455        /// Transient revision of the `Catalog` when this transaction started.
1456        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/// An `INSERT` waiting to be committed.
1480#[derive(Debug, Clone, PartialEq)]
1481pub struct WriteOp {
1482    /// The target table.
1483    pub id: CatalogItemId,
1484    /// The data rows.
1485    pub rows: TableData,
1486}
1487
1488/// Whether a transaction requires linearization.
1489#[derive(Debug)]
1490pub enum RequireLinearization {
1491    /// Linearization is required.
1492    Required,
1493    /// Linearization is not required.
1494    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/// A complete set of exclusive locks for writing to collections identified by [`CatalogItemId`]s.
1509///
1510/// To prevent deadlocks between two sessions, we do not allow acquiring a partial set of locks.
1511#[derive(Debug)]
1512pub struct WriteLocks {
1513    locks: BTreeMap<CatalogItemId, tokio::sync::OwnedMutexGuard<()>>,
1514    /// Connection that currently holds these locks, used for tracing purposes only.
1515    conn_id: ConnectionId,
1516}
1517
1518impl WriteLocks {
1519    /// Create a [`WriteLocksBuilder`] pre-defining all of the locks we need.
1520    ///
1521    /// When "finishing" the builder with [`WriteLocksBuilder::all_or_nothing`], if we haven't
1522    /// acquired all of the necessary locks we drop any partially acquired ones.
1523    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    /// Validate this set of [`WriteLocks`] is sufficient for the provided collections.
1529    /// Dropping the currently held locks if it's not.
1530    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            // Explicitly drop the already acquired locks.
1545            drop(self);
1546            Err(missing)
1547        }
1548    }
1549}
1550
1551impl Drop for WriteLocks {
1552    fn drop(&mut self) {
1553        // We may have merged the locks into GroupCommitWriteLocks, thus it could be empty.
1554        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/// A builder struct that helps us acquire all of the locks we need, or none of them.
1565///
1566/// See [`WriteLocks::builder`].
1567#[derive(Debug)]
1568pub struct WriteLocksBuilder {
1569    locks: BTreeMap<CatalogItemId, Option<tokio::sync::OwnedMutexGuard<()>>>,
1570}
1571
1572impl WriteLocksBuilder {
1573    /// Adds a lock to this builder.
1574    pub fn insert_lock(&mut self, id: CatalogItemId, lock: tokio::sync::OwnedMutexGuard<()>) {
1575        self.locks.insert(id, Some(lock));
1576    }
1577
1578    /// Finish this builder by returning either all of the necessary locks, or none of them.
1579    ///
1580    /// If we fail to acquire all of the locks, returns one of the [`CatalogItemId`]s that we
1581    /// failed to acquire a lock for, that should be awaited so we know when to run again.
1582    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                // Explicitly drop the already acquired locks.
1602                drop(locks);
1603                Err(*gid)
1604            }
1605        }
1606    }
1607}
1608
1609/// Collection of [`WriteLocks`] gathered during [`group_commit`].
1610///
1611/// Note: This struct should __never__ be used outside of group commit because it attempts to merge
1612/// together several collections of [`WriteLocks`] which if not done carefully can cause deadlocks
1613/// or consistency violations.
1614///
1615/// We must prevent writes from occurring to tables during read then write plans (e.g. `UPDATE`)
1616/// but we can allow blind writes (e.g. `INSERT`) to get committed concurrently at the same
1617/// timestamp when submitting the updates from a read then write plan.
1618///
1619/// Naively it would seem as though we could allow blind writes to occur whenever as blind writes
1620/// could never cause invalid retractions, but it could cause us to violate serializability because
1621/// there is no total order we could define for the transactions. Consider the following scenario:
1622///
1623/// ```text
1624/// table: foo
1625///
1626///  a | b
1627/// --------
1628///  x   2
1629///  y   3
1630///  z   4
1631///
1632/// -- Session(A)
1633/// -- read then write plan, reads at t0, writes at t3, transaction Ta
1634/// DELETE FROM foo WHERE b % 2 = 0;
1635///
1636///
1637/// -- Session(B)
1638/// -- blind write into foo, writes at t1, transaction Tb
1639/// INSERT INTO foo VALUES ('q', 6);
1640/// -- select from foo, reads at t2, transaction Tc
1641/// SELECT * FROM foo;
1642///
1643///
1644/// The times these operations occur at are ordered:
1645/// t0 < t1 < t2 < t3
1646///
1647/// Given the timing of the operations, the transactions must have the following order:
1648///
1649/// * Ta does not observe ('q', 6), so Ta < Tb
1650/// * Tc does observe ('q', 6), so Tb < Tc
1651/// * Tc does not observe the retractions from Ta, so Tc < Ta
1652///
1653/// For total order to exist, Ta < Tb < Tc < Ta, which is impossible.
1654/// ```
1655///
1656/// [`group_commit`]: super::coord::Coordinator::group_commit
1657#[derive(Debug, Default)]
1658pub(crate) struct GroupCommitWriteLocks {
1659    locks: BTreeMap<CatalogItemId, tokio::sync::OwnedMutexGuard<()>>,
1660}
1661
1662impl GroupCommitWriteLocks {
1663    /// Merge a set of [`WriteLocks`] into this collection for group commit.
1664    pub fn merge(&mut self, mut locks: WriteLocks) {
1665        // Note: Ideally we would use `.drain`, but that method doesn't exist for BTreeMap.
1666        //
1667        // See: <https://github.com/rust-lang/rust/issues/81074>
1668        let existing = std::mem::take(&mut locks.locks);
1669        self.locks.extend(existing);
1670    }
1671
1672    /// Returns the collections we're missing locks for, if any.
1673    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}