Skip to main content

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::BTreeMap;
15use std::collections::btree_map::Entry;
16use std::future::Future;
17use std::mem;
18use std::net::IpAddr;
19use std::sync::Arc;
20
21use chrono::{DateTime, Utc};
22use derivative::Derivative;
23use mz_adapter_types::connection::ConnectionId;
24use mz_auth::AuthenticatorKind;
25use mz_auth::user::ExternalUserMetadata;
26use mz_build_info::{BuildInfo, DUMMY_BUILD_INFO};
27use mz_controller_types::ClusterId;
28use mz_ore::metrics::{MetricsFutureExt, MetricsRegistry};
29use mz_ore::now::{EpochMillis, NowFn};
30use mz_pgwire_common::Format;
31use mz_repr::role_id::RoleId;
32use mz_repr::user::InternalUserMetadata;
33use mz_repr::{CatalogItemId, Datum, Row, RowIterator, SqlScalarType, Timestamp};
34use mz_sql::ast::{AstInfo, Raw, Statement, TransactionAccessMode};
35use mz_sql::plan::{Params, PlanContext, QueryWhen, StatementDesc};
36use mz_sql::session::metadata::SessionMetadata;
37use mz_sql::session::user::{
38    INTERNAL_USER_NAME_TO_DEFAULT_CLUSTER, RoleMetadata, SYSTEM_USER, User,
39};
40use mz_sql::session::vars::IsolationLevel;
41pub use mz_sql::session::vars::{
42    DEFAULT_DATABASE_NAME, EndTransactionAction, SERVER_MAJOR_VERSION, SERVER_MINOR_VERSION,
43    SERVER_PATCH_VERSION, SessionVars, Var,
44};
45use mz_sql_parser::ast::TransactionIsolationLevel;
46use mz_storage_client::client::TableData;
47use mz_storage_types::sources::Timeline;
48use qcell::{QCell, QCellOwner};
49use timely::progress::Timestamp as _;
50use tokio::sync::mpsc::{self, UnboundedSender};
51use tokio::sync::watch;
52use uuid::Uuid;
53
54use crate::AdapterNotice;
55use crate::ExecutionTime;
56use crate::catalog::CatalogState;
57use crate::client::RecordFirstRowStream;
58use crate::coord::ExplainContext;
59use crate::coord::appends::BuiltinTableAppendNotify;
60use crate::coord::in_memory_oracle::InMemoryTimestampOracle;
61use crate::coord::peek::PeekResponseUnary;
62use crate::coord::timestamp_selection::{TimestampContext, TimestampDetermination};
63use crate::error::AdapterError;
64use crate::metrics::{Metrics, SessionMetrics};
65use crate::notice::ExecutionTimeKind;
66use crate::statement_logging::PreparedStatementLoggingInfo;
67use mz_catalog::durable::Snapshot;
68
69pub(crate) const DUMMY_CONNECTION_ID: ConnectionId = ConnectionId::Static(0);
70
71/// A session holds per-connection state.
72#[derive(Derivative)]
73#[derivative(Debug)]
74pub struct Session {
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,
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 [`SessionConfig::user`].
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>,
121    /// Incremented when session state that is relevant to prepared statement planning may have
122    /// changed: `portals`, `prepared_statements`, anything a statement execution can change, such
123    /// as session variables, and the end of a transaction, which reverts `SET LOCAL`.
124    /// (`Catalog::transient_revision` similarly tracks changes on the catalog side.)
125    state_revision: u64,
126}
127
128impl SessionMetadata for Session {
129    fn conn_id(&self) -> &ConnectionId {
130        &self.conn_id
131    }
132
133    fn client_ip(&self) -> Option<&IpAddr> {
134        self.client_ip.as_ref()
135    }
136
137    fn pcx(&self) -> &PlanContext {
138        &self
139            .transaction()
140            .inner()
141            .expect("no active transaction")
142            .pcx
143    }
144
145    fn role_metadata(&self) -> &RoleMetadata {
146        self.role_metadata
147            .as_ref()
148            .expect("role_metadata invariant violated")
149    }
150
151    fn vars(&self) -> &SessionVars {
152        &self.vars
153    }
154}
155
156/// Data structure suitable for passing to other threads that need access to some common Session
157/// properties.
158#[derive(Debug)]
159pub struct SessionMeta {
160    conn_id: ConnectionId,
161    client_ip: Option<IpAddr>,
162    pcx: PlanContext,
163    role_metadata: RoleMetadata,
164    vars: SessionVars,
165}
166
167impl SessionMetadata for SessionMeta {
168    fn vars(&self) -> &SessionVars {
169        &self.vars
170    }
171
172    fn conn_id(&self) -> &ConnectionId {
173        &self.conn_id
174    }
175
176    fn client_ip(&self) -> Option<&IpAddr> {
177        self.client_ip.as_ref()
178    }
179
180    fn pcx(&self) -> &PlanContext {
181        &self.pcx
182    }
183
184    fn role_metadata(&self) -> &RoleMetadata {
185        &self.role_metadata
186    }
187}
188
189/// Configures a new [`Session`].
190#[derive(Debug, Clone)]
191pub struct SessionConfig {
192    /// The connection ID for the session.
193    ///
194    /// May be reused after the session terminates.
195    pub conn_id: ConnectionId,
196    /// A universally unique identifier for the session, across all processes,
197    /// region, and all time.
198    ///
199    /// Must not be reused, even after the session terminates.
200    pub uuid: Uuid,
201    /// The peer address of the client
202    pub client_ip: Option<IpAddr>,
203    /// The name of the user associated with the session.
204    pub user: String,
205    /// An optional receiver that the session will periodically check for
206    /// updates to a user's external metadata.
207    pub external_metadata_rx: Option<watch::Receiver<ExternalUserMetadata>>,
208    /// Helm chart version
209    pub helm_chart_version: Option<String>,
210    /// The authenticator that authenticated this user, if any.
211    pub authenticator_kind: AuthenticatorKind,
212    /// Groups from JWT claims for OIDC group-to-role sync.
213    pub groups: Option<Vec<String>>,
214}
215
216impl Session {
217    /// Creates a new session for the specified connection ID.
218    pub(crate) fn new(
219        build_info: &'static BuildInfo,
220        config: SessionConfig,
221        metrics: SessionMetrics,
222    ) -> Session {
223        assert_ne!(config.conn_id, DUMMY_CONNECTION_ID);
224        Self::new_internal(build_info, config, metrics)
225    }
226
227    /// Returns a reference-less collection of data usable by other tasks that don't have ownership
228    /// of the Session.
229    pub fn meta(&self) -> SessionMeta {
230        SessionMeta {
231            conn_id: self.conn_id().clone(),
232            client_ip: self.client_ip().copied(),
233            pcx: self.pcx().clone(),
234            role_metadata: self.role_metadata().clone(),
235            vars: self.vars.clone(),
236        }
237
238        // TODO: soft_assert that these are the same as Session.
239    }
240
241    /// Creates new statement logging metadata for a one-off
242    /// statement.
243    // Normally, such logging information would be created as part of
244    // allocating a new prepared statement, and a refcounted handle
245    // would be copied from that prepared statement to portals during
246    // binding. However, we also support (via `Command::declare`)
247    // binding a statement directly to a portal without creating an
248    // intermediate prepared statement. Thus, for those cases, a
249    // mechanism for generating the logging metadata directly is needed.
250    pub(crate) fn mint_logging<A: AstInfo>(
251        &self,
252        raw_sql: String,
253        stmt: Option<&Statement<A>>,
254        now: EpochMillis,
255    ) -> Arc<QCell<PreparedStatementLoggingInfo>> {
256        Arc::new(QCell::new(
257            &self.qcell_owner,
258            PreparedStatementLoggingInfo::still_to_log(
259                raw_sql,
260                stmt,
261                now,
262                "".to_string(),
263                self.uuid,
264                false,
265            ),
266        ))
267    }
268
269    pub(crate) fn qcell_ro<'a, T2: 'a>(&'a self, cell: &'a Arc<QCell<T2>>) -> &'a T2 {
270        self.qcell_owner.ro(&*cell)
271    }
272
273    pub(crate) fn qcell_rw<'a, T2: 'a>(&'a mut self, cell: &'a Arc<QCell<T2>>) -> &'a mut T2 {
274        self.qcell_owner.rw(&*cell)
275    }
276
277    /// Returns a unique ID for the session.
278    /// Not to be confused with `connection_id`, which can be reused.
279    pub fn uuid(&self) -> Uuid {
280        self.uuid
281    }
282
283    /// Creates a new dummy session.
284    ///
285    /// Dummy sessions are intended for use when executing queries on behalf of
286    /// the system itself, rather than on behalf of a user.
287    pub fn dummy() -> Session {
288        let registry = MetricsRegistry::new();
289        let metrics = Metrics::register_into(&registry);
290        let metrics = metrics.session_metrics();
291        let mut dummy = Self::new_internal(
292            &DUMMY_BUILD_INFO,
293            SessionConfig {
294                conn_id: DUMMY_CONNECTION_ID,
295                uuid: Uuid::new_v4(),
296                user: SYSTEM_USER.name.clone(),
297                client_ip: None,
298                external_metadata_rx: None,
299                helm_chart_version: None,
300                authenticator_kind: AuthenticatorKind::None,
301                groups: None,
302            },
303            metrics,
304        );
305        dummy.initialize_role_metadata(RoleId::User(0));
306        dummy
307    }
308
309    fn new_internal(
310        build_info: &'static BuildInfo,
311        SessionConfig {
312            conn_id,
313            uuid,
314            user,
315            client_ip,
316            mut external_metadata_rx,
317            helm_chart_version,
318            authenticator_kind,
319            groups,
320        }: SessionConfig,
321        metrics: SessionMetrics,
322    ) -> Session {
323        let (notices_tx, notices_rx) = mpsc::unbounded_channel();
324        let default_cluster = INTERNAL_USER_NAME_TO_DEFAULT_CLUSTER.get(&user);
325        let user = User {
326            name: user,
327            internal_metadata: None,
328            external_metadata: external_metadata_rx
329                .as_mut()
330                .map(|rx| rx.borrow_and_update().clone()),
331            authenticator_kind: Some(authenticator_kind),
332            groups,
333        };
334        let mut vars = SessionVars::new_unchecked(build_info, user, helm_chart_version);
335        if let Some(default_cluster) = default_cluster {
336            vars.set_cluster(default_cluster.clone());
337        }
338        Session {
339            conn_id,
340            uuid,
341            transaction: TransactionStatus::Default,
342            pcx: None,
343            metrics,
344            builtin_updates: None,
345            prepared_statements: BTreeMap::new(),
346            portals: BTreeMap::new(),
347            role_metadata: None,
348            client_ip,
349            vars,
350            notices_tx,
351            notices_rx,
352            next_transaction_id: 0,
353            secret_key: rand::random(),
354            external_metadata_rx,
355            qcell_owner: QCellOwner::new(),
356            session_oracles: BTreeMap::new(),
357            state_revision: 0,
358        }
359    }
360
361    /// Returns the secret key associated with the session.
362    pub fn secret_key(&self) -> u32 {
363        self.secret_key
364    }
365
366    fn new_pcx(&self, mut wall_time: DateTime<Utc>) -> PlanContext {
367        if let Some(mock_time) = self.vars().unsafe_new_transaction_wall_time() {
368            wall_time = *mock_time;
369        }
370        PlanContext::new(wall_time)
371    }
372
373    /// Starts an explicit transaction, or changes an implicit to an explicit
374    /// transaction.
375    pub fn start_transaction(
376        &mut self,
377        wall_time: DateTime<Utc>,
378        access: Option<TransactionAccessMode>,
379        isolation_level: Option<TransactionIsolationLevel>,
380    ) -> Result<(), AdapterError> {
381        // Check that current transaction state is compatible with new `access`
382        if let Some(txn) = self.transaction.inner() {
383            // `READ WRITE` prohibited if:
384            // - Currently in `READ ONLY`
385            // - Already performed a query
386            let read_write_prohibited = match txn.ops {
387                TransactionOps::Peeks { .. } | TransactionOps::Subscribe => {
388                    txn.access == Some(TransactionAccessMode::ReadOnly)
389                }
390                TransactionOps::None
391                | TransactionOps::Writes(_)
392                | TransactionOps::SingleStatement { .. }
393                | TransactionOps::DDL { .. } => false,
394            };
395
396            if read_write_prohibited && access == Some(TransactionAccessMode::ReadWrite) {
397                return Err(AdapterError::ReadWriteUnavailable);
398            }
399        }
400
401        match std::mem::take(&mut self.transaction) {
402            TransactionStatus::Default => {
403                let id = self.next_transaction_id;
404                self.next_transaction_id = self.next_transaction_id.wrapping_add(1);
405                self.transaction = TransactionStatus::InTransaction(Transaction {
406                    completion_owner: TransactionCompletionOwner::Coordinator,
407                    pcx: self.new_pcx(wall_time),
408                    ops: TransactionOps::None,
409                    pending_ddl_inspections: Vec::new(),
410                    contains_explain: false,
411                    access,
412                    id,
413                });
414            }
415            TransactionStatus::Started(mut txn)
416            | TransactionStatus::InTransactionImplicit(mut txn)
417            | TransactionStatus::InTransaction(mut txn) => {
418                if access.is_some() {
419                    txn.access = access;
420                }
421                self.transaction = TransactionStatus::InTransaction(txn);
422            }
423            TransactionStatus::Failed(_) => unreachable!(),
424        };
425
426        if let Some(isolation_level) = isolation_level {
427            self.vars
428                .set_local_transaction_isolation(isolation_level.into());
429        }
430
431        Ok(())
432    }
433
434    /// Starts either a single statement or implicit transaction based on the
435    /// number of statements, but only if no transaction has been started already.
436    pub fn start_transaction_implicit(&mut self, wall_time: DateTime<Utc>, stmts: usize) {
437        if let TransactionStatus::Default = self.transaction {
438            let id = self.next_transaction_id;
439            self.next_transaction_id = self.next_transaction_id.wrapping_add(1);
440            let txn = Transaction {
441                completion_owner: TransactionCompletionOwner::Session,
442                pcx: self.new_pcx(wall_time),
443                ops: TransactionOps::None,
444                pending_ddl_inspections: Vec::new(),
445                contains_explain: false,
446                access: None,
447                id,
448            };
449            match stmts {
450                1 => self.transaction = TransactionStatus::Started(txn),
451                n if n > 1 => self.transaction = TransactionStatus::InTransactionImplicit(txn),
452                _ => {}
453            }
454        }
455    }
456
457    /// Starts a single statement transaction, but only if no transaction has been started already.
458    pub fn start_transaction_single_stmt(&mut self, wall_time: DateTime<Utc>) {
459        self.start_transaction_implicit(wall_time, 1);
460    }
461
462    /// Clears a transaction, setting its state to Default and destroying all
463    /// portals. Returned are:
464    /// - sinks that were started in this transaction and need to be dropped
465    /// - the cleared transaction so its operations can be handled
466    ///
467    /// The [Postgres protocol docs](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) specify:
468    /// > a named portal object lasts till the end of the current transaction
469    /// and
470    /// > An unnamed portal is destroyed at the end of the transaction
471    #[must_use]
472    pub fn clear_transaction(&mut self) -> TransactionStatus {
473        self.portals.clear();
474        self.pcx = None;
475        self.state_revision += 1;
476        mem::take(&mut self.transaction)
477    }
478
479    /// Transfers transaction completion to the coordinator. Call before handing it any
480    /// transaction-scoped state, including on paths that can fail after installing resources.
481    pub(crate) fn require_coordinator_completion(&mut self) {
482        if let Some(txn) = self.transaction.inner_mut() {
483            txn.completion_owner = TransactionCompletionOwner::Coordinator;
484        }
485    }
486
487    /// Returns the obligations for a session-owned read-only completion.
488    pub(crate) fn read_only_completion(
489        &self,
490        mut action: EndTransactionAction,
491    ) -> Option<ReadOnlyCompletion> {
492        let txn = self.transaction.inner()?;
493        if txn.completion_owner != TransactionCompletionOwner::Session {
494            return None;
495        }
496        let timestamp = match &txn.ops {
497            TransactionOps::None => None,
498            TransactionOps::Peeks {
499                determination,
500                requires_linearization,
501                ..
502            } => matches!(requires_linearization, RequireLinearization::Required)
503                .then(|| determination.timestamp_context.clone()),
504            TransactionOps::Writes(_)
505            | TransactionOps::Subscribe
506            | TransactionOps::SingleStatement { .. }
507            | TransactionOps::DDL { .. } => return None,
508        };
509        if matches!(self.transaction, TransactionStatus::Failed(_)) {
510            action = EndTransactionAction::Rollback;
511        }
512        Some(ReadOnlyCompletion {
513            action,
514            timestamp: if action == EndTransactionAction::Commit {
515                timestamp
516            } else {
517                None
518            },
519        })
520    }
521
522    /// Marks the current transaction as failed.
523    pub fn fail_transaction(mut self) -> Self {
524        match self.transaction {
525            TransactionStatus::Default => unreachable!(),
526            TransactionStatus::Started(txn)
527            | TransactionStatus::InTransactionImplicit(txn)
528            | TransactionStatus::InTransaction(txn) => {
529                self.transaction = TransactionStatus::Failed(txn);
530            }
531            TransactionStatus::Failed(_) => {}
532        };
533        self
534    }
535
536    /// Returns the current transaction status.
537    pub fn transaction(&self) -> &TransactionStatus {
538        &self.transaction
539    }
540
541    /// Returns the current transaction status.
542    pub fn transaction_mut(&mut self) -> &mut TransactionStatus {
543        &mut self.transaction
544    }
545
546    /// Returns the session's transaction code.
547    pub fn transaction_code(&self) -> TransactionCode {
548        self.transaction().into()
549    }
550
551    /// Retains a SHOW CREATE result for validation if this transaction commits DDL.
552    pub(crate) fn retain_catalog_result(
553        &mut self,
554        command: Arc<crate::catalog::command::CatalogResultCommand>,
555    ) {
556        self.retain_ddl_inspection(DdlInspection::CatalogResult(command));
557    }
558
559    fn retain_ddl_inspection(&mut self, inspection: DdlInspection) {
560        if !self.transaction().can_retain_ddl_inspections() {
561            return;
562        }
563        let txn = self
564            .transaction_mut()
565            .inner_mut()
566            .expect("active transaction");
567        match &mut txn.ops {
568            TransactionOps::DDL { commands, .. } => commands.push(inspection.into_command()),
569            _ => txn.pending_ddl_inspections.push(inspection),
570        }
571    }
572
573    /// Retains a successful statement description for validation at DDL commit.
574    pub(crate) fn retain_description(
575        &mut self,
576        statement: mz_sql::ast::Statement<mz_sql::ast::Raw>,
577        param_types: Vec<Option<mz_repr::SqlScalarType>>,
578        expected: mz_sql::plan::StatementDesc,
579    ) {
580        if !self.transaction().can_retain_ddl_inspections()
581            || (expected.relation_desc.is_none() && expected.param_types.is_empty())
582        {
583            return;
584        }
585        // DECLARE delegates description to its inner statement. EXECUTE and FETCH
586        // copy session-owned schemas without describing a catalog query.
587        let mut described = &statement;
588        while let mz_sql::ast::Statement::Declare(declare) = described {
589            described = &declare.stmt;
590        }
591        if matches!(
592            described,
593            mz_sql::ast::Statement::Execute(_) | mz_sql::ast::Statement::Fetch(_)
594        ) {
595            return;
596        }
597        let command = crate::catalog::command::DescriptionCommand::new(
598            statement,
599            param_types,
600            self.meta(),
601            expected,
602        );
603        self.retain_ddl_inspection(DdlInspection::Description(Arc::new(command)));
604    }
605
606    /// Adds operations, rejecting incompatible combinations of reads and writes.
607    pub fn add_transaction_ops(&mut self, add_ops: TransactionOps) -> Result<(), AdapterError> {
608        self.transaction.add_ops(add_ops)
609    }
610
611    /// Returns a channel on which to send notices to the session.
612    pub fn retain_notice_transmitter(&self) -> UnboundedSender<AdapterNotice> {
613        self.notices_tx.clone()
614    }
615
616    /// Adds a notice to the session.
617    pub fn add_notice(&self, notice: AdapterNotice) {
618        self.add_notices([notice])
619    }
620
621    /// Adds multiple notices to the session.
622    pub fn add_notices(&self, notices: impl IntoIterator<Item = AdapterNotice>) {
623        for notice in notices {
624            let _ = self.notices_tx.send(notice);
625        }
626    }
627
628    /// Awaits a possible notice.
629    ///
630    /// This method is cancel safe.
631    pub async fn recv_notice(&mut self) -> AdapterNotice {
632        // This method is cancel safe because recv is cancel safe.
633        loop {
634            let notice = self
635                .notices_rx
636                .recv()
637                .await
638                .expect("Session also holds a sender, so recv won't ever return None");
639            match self.notice_filter(notice) {
640                Some(notice) => return notice,
641                None => continue,
642            }
643        }
644    }
645
646    /// Returns a draining iterator over the notices attached to the session.
647    pub fn drain_notices(&mut self) -> Vec<AdapterNotice> {
648        let mut notices = Vec::new();
649        while let Ok(notice) = self.notices_rx.try_recv() {
650            if let Some(notice) = self.notice_filter(notice) {
651                notices.push(notice);
652            }
653        }
654        notices
655    }
656
657    /// Builds a timing notice if enabled and admitted by `client_min_messages`.
658    pub fn execution_time_notice(&self, time: ExecutionTime) -> Option<AdapterNotice> {
659        if !self.vars.emit_execution_time_notice() {
660            return None;
661        }
662        self.notice_filter(AdapterNotice::ExecutionTime(time))
663    }
664
665    /// Returns `time` with the kind `staged` if the current transaction holds work for its commit,
666    /// and `time` unchanged otherwise.
667    ///
668    /// Must be called before the statement settles, because settling can commit that work. A
669    /// statement that follows such work in the same transaction is marked too.
670    pub fn maybe_mark_staged(&self, time: ExecutionTime) -> ExecutionTime {
671        let staged = self
672            .transaction()
673            .inner()
674            .is_some_and(|txn| txn.ops.stages_work());
675        if staged {
676            ExecutionTime {
677                kind: ExecutionTimeKind::Staged,
678                ..time
679            }
680        } else {
681            time
682        }
683    }
684
685    /// Returns Some if the notice should be reported, otherwise None.
686    fn notice_filter(&self, notice: AdapterNotice) -> Option<AdapterNotice> {
687        // Filter out low threshold severity.
688        let minimum_client_severity = self.vars.client_min_messages();
689        let sev = notice.severity();
690        if !minimum_client_severity.should_output_to_client(&sev) {
691            return None;
692        }
693        // Filter out notices for other clusters.
694        if let AdapterNotice::ClusterReplicaStatusChanged { cluster, .. } = &notice {
695            if cluster != self.vars.cluster() {
696                return None;
697            }
698        }
699        Some(notice)
700    }
701
702    /// Sets the transaction ops to `TransactionOps::None`. Must only be used after
703    /// verifying that no transaction anomalies will occur if cleared.
704    pub fn clear_transaction_ops(&mut self) {
705        if let Some(txn) = self.transaction.inner_mut() {
706            txn.ops = TransactionOps::None;
707        }
708    }
709
710    /// Returns the transaction's read timestamp determination, if set.
711    ///
712    /// Returns `None` if there is no active transaction, or if the active
713    /// transaction is not a read transaction.
714    pub fn get_transaction_timestamp_determination(&self) -> Option<TimestampDetermination> {
715        match self.transaction.inner() {
716            Some(Transaction {
717                pcx: _,
718                ops: TransactionOps::Peeks { determination, .. },
719                access: _,
720                id: _,
721                pending_ddl_inspections: _,
722                contains_explain: _,
723                completion_owner: _,
724            }) => Some(determination.clone()),
725            _ => None,
726        }
727    }
728
729    /// Whether this session has a timestamp for a read transaction.
730    pub fn contains_read_timestamp(&self) -> bool {
731        matches!(
732            self.transaction.inner(),
733            Some(Transaction {
734                pcx: _,
735                ops: TransactionOps::Peeks {
736                    determination: TimestampDetermination {
737                        timestamp_context: TimestampContext::TimelineTimestamp { .. },
738                        ..
739                    },
740                    ..
741                },
742                access: _,
743                id: _,
744                pending_ddl_inspections: _,
745                contains_explain: _,
746                completion_owner: _,
747            })
748        )
749    }
750
751    /// Registers the prepared statement under `name`.
752    pub fn set_prepared_statement(
753        &mut self,
754        name: String,
755        stmt: Option<Statement<Raw>>,
756        raw_sql: String,
757        desc: StatementDesc,
758        state_revision: StateRevision,
759        now: EpochMillis,
760    ) {
761        let state_revision = self.advance_state_revision_for_insert(state_revision);
762        let logging = PreparedStatementLoggingInfo::still_to_log(
763            raw_sql,
764            stmt.as_ref(),
765            now,
766            name.clone(),
767            self.uuid,
768            false,
769        );
770        let statement = PreparedStatement {
771            stmt,
772            desc,
773            state_revision,
774            logging: Arc::new(QCell::new(&self.qcell_owner, logging)),
775        };
776        self.prepared_statements.insert(name, statement);
777    }
778
779    /// Removes the prepared statement associated with `name`.
780    ///
781    /// Returns whether a statement previously existed.
782    pub fn remove_prepared_statement(&mut self, name: &str) -> bool {
783        let removed = self.prepared_statements.remove(name).is_some();
784        if removed {
785            self.state_revision += 1;
786        }
787        removed
788    }
789
790    /// Removes all prepared statements.
791    pub fn remove_all_prepared_statements(&mut self) {
792        self.state_revision += 1;
793        self.prepared_statements.clear();
794    }
795
796    /// Retrieves the prepared statement associated with `name`.
797    ///
798    /// This is unverified and could be incorrect if the underlying catalog has
799    /// changed.
800    pub fn get_prepared_statement_unverified(&self, name: &str) -> Option<&PreparedStatement> {
801        self.prepared_statements.get(name)
802    }
803
804    /// Retrieves the prepared statement associated with `name`.
805    ///
806    /// This is unverified and could be incorrect if the underlying catalog has
807    /// changed.
808    pub fn get_prepared_statement_mut_unverified(
809        &mut self,
810        name: &str,
811    ) -> Option<&mut PreparedStatement> {
812        self.prepared_statements.get_mut(name)
813    }
814
815    /// Returns the prepared statements for the session.
816    pub fn prepared_statements(&self) -> &BTreeMap<String, PreparedStatement> {
817        &self.prepared_statements
818    }
819
820    /// Returns the portals for the session.
821    pub fn portals(&self) -> &BTreeMap<String, Portal> {
822        &self.portals
823    }
824
825    /// Binds the specified portal to the specified prepared statement.
826    ///
827    /// If the prepared statement contains parameters, the values and types of
828    /// those parameters must be provided in `params`. It is the caller's
829    /// responsibility to ensure that the correct number of parameters is
830    /// provided.
831    ///
832    /// The `results_formats` parameter sets the desired format of the results,
833    /// and is stored on the portal.
834    pub fn set_portal(
835        &mut self,
836        portal_name: String,
837        desc: StatementDesc,
838        stmt: Option<Statement<Raw>>,
839        logging: Arc<QCell<PreparedStatementLoggingInfo>>,
840        params: Vec<(Datum, SqlScalarType)>,
841        result_formats: Vec<Format>,
842        state_revision: StateRevision,
843    ) -> Result<(), AdapterError> {
844        // The empty portal can be silently replaced.
845        if !portal_name.is_empty() && self.portals.contains_key(&portal_name) {
846            return Err(AdapterError::DuplicateCursor(portal_name));
847        }
848        let state_revision = self.advance_state_revision_for_insert(state_revision);
849        let param_types = desc.param_types.clone();
850        self.portals.insert(
851            portal_name,
852            Portal {
853                stmt: stmt.map(Arc::new),
854                desc,
855                state_revision,
856                parameters: Params {
857                    datums: Row::pack(params.iter().map(|(d, _t)| d)),
858                    execute_types: params.into_iter().map(|(_d, t)| t).collect(),
859                    expected_types: param_types,
860                },
861                result_formats,
862                state: PortalState::NotStarted,
863                logging,
864                lifecycle_timestamps: None,
865            },
866        );
867        Ok(())
868    }
869
870    /// Removes the specified portal.
871    ///
872    /// If there is no such portal, this method does nothing. Returns whether that portal existed.
873    pub fn remove_portal(&mut self, portal_name: &str) -> bool {
874        self.state_revision += 1;
875        self.portals.remove(portal_name).is_some()
876    }
877
878    /// Retrieves a reference to the specified portal.
879    ///
880    /// If there is no such portal, returns `None`.
881    pub fn get_portal_unverified(&self, portal_name: &str) -> Option<&Portal> {
882        self.portals.get(portal_name)
883    }
884
885    /// Retrieves a mutable reference to the specified portal.
886    ///
887    /// If there is no such portal, returns `None`.
888    ///
889    /// Note: When using the returned `PortalRefMut`, there is no need to increment
890    /// `Session::state_revision`, because the portal's meaning is not changed.
891    pub fn get_portal_unverified_mut(&mut self, portal_name: &str) -> Option<PortalRefMut<'_>> {
892        self.portals.get_mut(portal_name).map(|p| PortalRefMut {
893            stmt: &p.stmt,
894            desc: &p.desc,
895            state_revision: &mut p.state_revision,
896            parameters: &mut p.parameters,
897            result_formats: &mut p.result_formats,
898            logging: &mut p.logging,
899            state: &mut p.state,
900            lifecycle_timestamps: &mut p.lifecycle_timestamps,
901        })
902    }
903
904    /// Creates and installs a new portal.
905    pub fn create_new_portal(
906        &mut self,
907        stmt: Option<Statement<Raw>>,
908        logging: Arc<QCell<PreparedStatementLoggingInfo>>,
909        desc: StatementDesc,
910        parameters: Params,
911        result_formats: Vec<Format>,
912        state_revision: StateRevision,
913    ) -> Result<String, AdapterError> {
914        let state_revision = self.advance_state_revision_for_insert(state_revision);
915
916        // See: https://github.com/postgres/postgres/blob/84f5c2908dad81e8622b0406beea580e40bb03ac/src/backend/utils/mmgr/portalmem.c#L234
917        for i in self.portals.len().. {
918            let name = format!("<unnamed portal {}>", i);
919            match self.portals.entry(name.clone()) {
920                Entry::Occupied(_) => continue,
921                Entry::Vacant(entry) => {
922                    entry.insert(Portal {
923                        stmt: stmt.map(Arc::new),
924                        desc,
925                        state_revision,
926                        parameters,
927                        result_formats,
928                        state: PortalState::NotStarted,
929                        logging,
930                        lifecycle_timestamps: None,
931                    });
932                    return Ok(name);
933                }
934            }
935        }
936
937        coord_bail!("unable to create a new portal");
938    }
939
940    /// Resets the session to its initial state.
941    ///
942    /// Returns the parameters changed by [`SessionVars::reset_all`].
943    pub fn reset(&mut self) -> BTreeMap<&'static str, String> {
944        let _ = self.clear_transaction();
945        self.remove_all_prepared_statements();
946        self.vars.reset_all()
947    }
948
949    /// Returns the [application_name] that created this session.
950    ///
951    /// [application_name]: (https://www.postgresql.org/docs/current/runtime-config-logging.html#GUC-APPLICATION-NAME)
952    pub fn application_name(&self) -> &str {
953        self.vars.application_name()
954    }
955
956    /// Returns a reference to the variables in this session.
957    pub fn vars(&self) -> &SessionVars {
958        &self.vars
959    }
960
961    /// Returns a mutable reference to the variables in this session.
962    pub fn vars_mut(&mut self) -> &mut SessionVars {
963        &mut self.vars
964    }
965
966    /// Drains any external metadata updates and applies the changes from the latest update.
967    pub fn apply_external_metadata_updates(&mut self) {
968        // If no sender is registered then there isn't anything to do.
969        let Some(rx) = &mut self.external_metadata_rx else {
970            return;
971        };
972
973        // If the value hasn't changed then return.
974        if !rx.has_changed().unwrap_or(false) {
975            return;
976        }
977
978        // Update our metadata! Note the short critical section (just a clone) to avoid blocking
979        // the sending side of this watch channel.
980        let metadata = rx.borrow_and_update().clone();
981        self.vars.set_external_user_metadata(metadata);
982    }
983
984    /// Applies the internal user metadata to the session.
985    pub fn apply_internal_user_metadata(&mut self, metadata: InternalUserMetadata) {
986        self.vars.set_internal_user_metadata(metadata);
987    }
988
989    /// Initializes the session's role metadata.
990    pub fn initialize_role_metadata(&mut self, role_id: RoleId) {
991        self.role_metadata = Some(RoleMetadata::new(role_id));
992    }
993
994    /// Ensures that a timestamp oracle exists for `timeline` and returns a mutable reference to
995    /// the timestamp oracle.
996    pub fn ensure_timestamp_oracle(&mut self, timeline: Timeline) -> &mut InMemoryTimestampOracle {
997        self.session_oracles.entry(timeline).or_insert_with(|| {
998            InMemoryTimestampOracle::new(Timestamp::minimum(), NowFn::from(Timestamp::minimum))
999        })
1000    }
1001
1002    /// Ensures that a timestamp oracle exists for reads and writes from/to a local input and
1003    /// returns a mutable reference to the timestamp oracle.
1004    pub fn ensure_local_timestamp_oracle(&mut self) -> &mut InMemoryTimestampOracle {
1005        self.ensure_timestamp_oracle(Timeline::EpochMilliseconds)
1006    }
1007
1008    /// Returns a reference to the timestamp oracle for `timeline`.
1009    pub fn get_timestamp_oracle(&self, timeline: &Timeline) -> Option<&InMemoryTimestampOracle> {
1010        self.session_oracles.get(timeline)
1011    }
1012
1013    /// If the current session is using the Strong Session Serializable isolation level advance the
1014    /// session local timestamp oracle to `write_ts`.
1015    pub fn apply_write(&mut self, timestamp: Timestamp) {
1016        if self.vars().transaction_isolation() == &IsolationLevel::StrongSessionSerializable {
1017            self.ensure_local_timestamp_oracle().apply_write(timestamp);
1018        }
1019    }
1020
1021    /// Returns the [`SessionMetrics`] instance associated with this [`Session`].
1022    pub fn metrics(&self) -> &SessionMetrics {
1023        &self.metrics
1024    }
1025
1026    /// Sets the `BuiltinTableAppendNotify` for this session.
1027    pub fn set_builtin_table_updates(&mut self, fut: BuiltinTableAppendNotify) {
1028        let prev = self.builtin_updates.replace(fut);
1029        mz_ore::soft_assert_or_log!(prev.is_none(), "replacing old builtin table notify");
1030    }
1031
1032    /// Takes the stashed `BuiltinTableAppendNotify`, if one exists, and returns a [`Future`] that
1033    /// waits for the writes to complete.
1034    pub fn clear_builtin_table_updates(&mut self) -> Option<impl Future<Output = ()> + 'static> {
1035        if let Some(fut) = self.builtin_updates.take() {
1036            // Record how long we blocked for, if we blocked at all.
1037            let histogram = self
1038                .metrics()
1039                .session_startup_table_writes_seconds()
1040                .clone();
1041            Some(async move {
1042                fut.wall_time().observe(histogram).await;
1043            })
1044        } else {
1045            None
1046        }
1047    }
1048
1049    /// Return the state_revision of the session, which can be used by dependent objects for knowing
1050    /// when to re-plan due to session state changes.
1051    pub fn state_revision(&self) -> u64 {
1052        self.state_revision
1053    }
1054
1055    /// Advances the state revision after a statement execution.
1056    pub(crate) fn advance_state_revision(&mut self) {
1057        self.state_revision += 1;
1058    }
1059
1060    /// Advances the state revision for inserting a prepared statement or portal verified at
1061    /// `verified`, and returns the revision to record on it.
1062    fn advance_state_revision_for_insert(&mut self, mut verified: StateRevision) -> StateRevision {
1063        let was_current = verified.session_state_revision == self.state_revision;
1064        self.state_revision += 1;
1065        // An entry's own insertion does not invalidate it.
1066        if was_current {
1067            verified.session_state_revision = self.state_revision;
1068        }
1069        verified
1070    }
1071}
1072
1073/// A prepared statement.
1074#[derive(Derivative, Clone)]
1075#[derivative(Debug)]
1076pub struct PreparedStatement {
1077    stmt: Option<Statement<Raw>>,
1078    desc: StatementDesc,
1079    /// The most recent state revision that has verified this statement.
1080    pub state_revision: StateRevision,
1081    #[derivative(Debug = "ignore")]
1082    logging: Arc<QCell<PreparedStatementLoggingInfo>>,
1083}
1084
1085impl PreparedStatement {
1086    /// Returns the AST associated with this prepared statement,
1087    /// if the prepared statement was not the empty query.
1088    pub fn stmt(&self) -> Option<&Statement<Raw>> {
1089        self.stmt.as_ref()
1090    }
1091
1092    /// Returns the description of the prepared statement.
1093    pub fn desc(&self) -> &StatementDesc {
1094        &self.desc
1095    }
1096
1097    /// Returns a handle to the metadata for statement logging.
1098    pub fn logging(&self) -> &Arc<QCell<PreparedStatementLoggingInfo>> {
1099        &self.logging
1100    }
1101}
1102
1103/// A portal represents the execution state of a running or runnable query.
1104#[derive(Derivative)]
1105#[derivative(Debug)]
1106pub struct Portal {
1107    /// The statement that is bound to this portal.
1108    pub stmt: Option<Arc<Statement<Raw>>>,
1109    /// The statement description.
1110    pub desc: StatementDesc,
1111    /// The most recent state revision that has verified this portal.
1112    pub state_revision: StateRevision,
1113    /// The bound values for the parameters in the prepared statement, if any.
1114    pub parameters: Params,
1115    /// The desired output format for each column in the result set.
1116    pub result_formats: Vec<Format>,
1117    /// A handle to metadata needed for statement logging.
1118    #[derivative(Debug = "ignore")]
1119    pub logging: Arc<QCell<PreparedStatementLoggingInfo>>,
1120    /// The execution state of the portal.
1121    #[derivative(Debug = "ignore")]
1122    pub state: PortalState,
1123    /// Statement lifecycle timestamps coming from `mz-pgwire`.
1124    pub lifecycle_timestamps: Option<LifecycleTimestamps>,
1125}
1126
1127/// A mutable reference to a portal, capturing its state and associated metadata. Importantly, it
1128/// does _not_ give _mutable_ access to `stmt` and `desc`, which means that you do not need to
1129/// increment `Session::state_revision` when modifying fields through a `PortalRefMut`, because the
1130/// portal's meaning is not changed.
1131pub struct PortalRefMut<'a> {
1132    /// The statement that is bound to this portal.
1133    pub stmt: &'a Option<Arc<Statement<Raw>>>,
1134    /// The statement description.
1135    pub desc: &'a StatementDesc,
1136    /// The most recent state revision that has verified this portal.
1137    pub state_revision: &'a mut StateRevision,
1138    /// The bound values for the parameters in the prepared statement, if any.
1139    pub parameters: &'a mut Params,
1140    /// The desired output format for each column in the result set.
1141    pub result_formats: &'a mut Vec<Format>,
1142    /// A handle to metadata needed for statement logging.
1143    pub logging: &'a mut Arc<QCell<PreparedStatementLoggingInfo>>,
1144    /// The execution state of the portal.
1145    pub state: &'a mut PortalState,
1146    /// Statement lifecycle timestamps coming from `mz-pgwire`.
1147    pub lifecycle_timestamps: &'a mut Option<LifecycleTimestamps>,
1148}
1149
1150/// Points to a revision of catalog state and session state. When the current revisions are not the
1151/// same as the revisions when a prepared statement or a portal was described, we need to check
1152/// whether the description is still valid.
1153#[derive(Debug, Clone, Copy, PartialEq)]
1154pub struct StateRevision {
1155    /// A revision of the catalog.
1156    pub catalog_revision: u64,
1157    /// A revision of the session state.
1158    pub session_state_revision: u64,
1159}
1160
1161/// Execution states of a portal.
1162pub enum PortalState {
1163    /// Portal not yet started.
1164    NotStarted,
1165    /// Portal is a rows-returning statement in progress with 0 or more rows
1166    /// remaining.
1167    InProgress(Option<InProgressRows>),
1168    /// Portal has completed and should not be re-executed. If the optional string
1169    /// is present, it is returned as a CommandComplete tag, otherwise an error
1170    /// is sent.
1171    Completed(Option<String>),
1172}
1173
1174/// State of an in-progress, rows-returning portal.
1175pub struct InProgressRows {
1176    /// The current batch of rows.
1177    pub current: Option<Box<dyn RowIterator + Send + Sync>>,
1178    /// A stream from which to fetch more row batches.
1179    pub remaining: RecordFirstRowStream,
1180}
1181
1182impl InProgressRows {
1183    /// Creates a new InProgressRows from a batch stream.
1184    pub fn new(remaining: RecordFirstRowStream) -> Self {
1185        Self {
1186            current: None,
1187            remaining,
1188        }
1189    }
1190
1191    /// Determines whether the underlying stream has ended and there are also no more rows
1192    /// stashed in `current`.
1193    pub fn no_more_rows(&self) -> bool {
1194        self.remaining.no_more_rows && self.current.is_none()
1195    }
1196}
1197
1198/// A stream of batched rows delivered to a client writer.
1199///
1200/// This is a boxed stream, not a bare channel receiver, so the coordinator can
1201/// insert an adapter between itself and the client writer. The SUBSCRIBE path
1202/// wraps the receiver in a byte-accounting `map` whose closure type cannot be
1203/// named, so it has to be boxed. Consumers box the receiver into a
1204/// `RecordFirstRowStream` regardless, so this adds no allocation.
1205pub type RowBatchStream = Box<dyn futures::Stream<Item = PeekResponseUnary> + Unpin + Send + Sync>;
1206
1207/// Part of statement lifecycle. These are timestamps that come from the Adapter frontend
1208/// (`mz-pgwire`) part of the lifecycle.
1209#[derive(Debug, Clone)]
1210pub struct LifecycleTimestamps {
1211    /// When the query was received. More specifically, when the tokio recv returned.
1212    /// For a Simple Query, this is for the whole query, for the Extended Query flow, this is only
1213    /// for `FrontendMessage::Execute`. (This means that this is after parsing for the
1214    /// Extended Query flow.)
1215    pub received: EpochMillis,
1216}
1217
1218impl LifecycleTimestamps {
1219    /// Creates a new `LifecycleTimestamps`.
1220    pub fn new(received: EpochMillis) -> Self {
1221        Self { received }
1222    }
1223}
1224
1225/// The transaction status of a session.
1226///
1227/// PostgreSQL's transaction states are in backend/access/transam/xact.c.
1228#[derive(Debug)]
1229pub enum TransactionStatus {
1230    /// Idle. Matches `TBLOCK_DEFAULT`.
1231    Default,
1232    /// Running a transaction started outside of any `BEGIN`. Matches
1233    /// `TBLOCK_STARTED`. In PostgreSQL, when using the extended query protocol, this
1234    /// may be upgraded into multi-statement implicit query (see [`Self::InTransactionImplicit`]).
1235    /// Additionally, some statements may trigger an eager commit of the implicit transaction,
1236    /// see: <https://git.postgresql.org/gitweb/?p=postgresql.git&a=commitdiff&h=f92944137>. In
1237    /// Materialize we never upgrade it. We eagerly commit it unless it can take on further
1238    /// statements of the same pipeline, see [`Self::may_span_pipeline`].
1239    Started(Transaction),
1240    /// Currently in a transaction issued from a `BEGIN`. Matches `TBLOCK_INPROGRESS`.
1241    InTransaction(Transaction),
1242    /// Currently in an implicit transaction started from a multi-statement query
1243    /// with more than 1 statements. Matches `TBLOCK_IMPLICIT_INPROGRESS`.
1244    InTransactionImplicit(Transaction),
1245    /// In a failed transaction. Matches `TBLOCK_ABORT`.
1246    Failed(Transaction),
1247}
1248
1249impl TransactionStatus {
1250    /// Extracts the inner transaction ops if not failed.
1251    pub fn into_ops(self) -> Option<TransactionOps> {
1252        match self {
1253            TransactionStatus::Default | TransactionStatus::Failed(_) => None,
1254            TransactionStatus::Started(txn)
1255            | TransactionStatus::InTransaction(txn)
1256            | TransactionStatus::InTransactionImplicit(txn) => Some(txn.ops),
1257        }
1258    }
1259
1260    /// Exposes the inner transaction.
1261    pub fn inner(&self) -> Option<&Transaction> {
1262        match self {
1263            TransactionStatus::Default => None,
1264            TransactionStatus::Started(txn)
1265            | TransactionStatus::InTransaction(txn)
1266            | TransactionStatus::InTransactionImplicit(txn)
1267            | TransactionStatus::Failed(txn) => Some(txn),
1268        }
1269    }
1270
1271    /// Exposes the inner transaction.
1272    pub fn inner_mut(&mut self) -> Option<&mut Transaction> {
1273        match self {
1274            TransactionStatus::Default => None,
1275            TransactionStatus::Started(txn)
1276            | TransactionStatus::InTransaction(txn)
1277            | TransactionStatus::InTransactionImplicit(txn)
1278            | TransactionStatus::Failed(txn) => Some(txn),
1279        }
1280    }
1281
1282    /// Whether inspections must be retained for a possible DDL commit.
1283    ///
1284    /// This includes observations made before the first DDL statement. Once the
1285    /// transaction cannot enter DDL mode, retaining their statements and session
1286    /// metadata would consume memory without any commit-time validation.
1287    fn can_retain_ddl_inspections(&self) -> bool {
1288        match self {
1289            Self::Started(txn) | Self::InTransaction(txn) | Self::InTransactionImplicit(txn) => {
1290                !txn.contains_explain
1291                    && match txn.ops {
1292                        TransactionOps::None | TransactionOps::DDL { .. } => true,
1293                        TransactionOps::Peeks { .. }
1294                        | TransactionOps::Writes(_)
1295                        | TransactionOps::Subscribe
1296                        | TransactionOps::SingleStatement { .. } => false,
1297                    }
1298            }
1299            Self::Default | Self::Failed(_) => false,
1300        }
1301    }
1302
1303    /// Records EXPLAIN execution, rejecting transactions that already contain DDL.
1304    pub(crate) fn record_explain(&mut self) -> Result<(), AdapterError> {
1305        let txn = self.inner_mut().expect("active transaction");
1306        if matches!(txn.ops, TransactionOps::DDL { .. }) {
1307            return Err(AdapterError::DDLOnlyTransaction);
1308        }
1309        // EXPLAIN outcomes are not replayed at commit, so this transaction must
1310        // not subsequently enter DDL mode and rebind its writes.
1311        txn.contains_explain = true;
1312        txn.pending_ddl_inspections.clear();
1313        Ok(())
1314    }
1315
1316    /// Whether the transaction's ops are DDL.
1317    pub fn is_ddl(&self) -> bool {
1318        match self {
1319            TransactionStatus::Default => false,
1320            TransactionStatus::Started(txn)
1321            | TransactionStatus::InTransaction(txn)
1322            | TransactionStatus::InTransactionImplicit(txn)
1323            | TransactionStatus::Failed(txn) => {
1324                matches!(txn.ops, TransactionOps::DDL { .. })
1325            }
1326        }
1327    }
1328
1329    /// Expresses whether or not the transaction was implicitly started.
1330    /// However, its negation does not imply explicitly started.
1331    pub fn is_implicit(&self) -> bool {
1332        match self {
1333            TransactionStatus::Started(_) | TransactionStatus::InTransactionImplicit(_) => true,
1334            TransactionStatus::Default
1335            | TransactionStatus::InTransaction(_)
1336            | TransactionStatus::Failed(_) => false,
1337        }
1338    }
1339
1340    /// Whether this implicit transaction may stay open for the rest of its
1341    /// extended-protocol pipeline, so that the pipeline commits or rolls back as a
1342    /// unit like PostgreSQL's.
1343    ///
1344    /// Only writes may, because they are merely staged. A read already pinned its
1345    /// timestamp without timedomain read holds, so a second read could neither join
1346    /// that timestamp nor pick its own.
1347    pub fn may_span_pipeline(&self) -> bool {
1348        match self {
1349            TransactionStatus::Started(txn) => match &txn.ops {
1350                TransactionOps::Writes(_) => true,
1351                TransactionOps::None
1352                | TransactionOps::Peeks { .. }
1353                | TransactionOps::Subscribe
1354                | TransactionOps::SingleStatement { .. }
1355                | TransactionOps::DDL { .. } => false,
1356            },
1357            TransactionStatus::Default
1358            | TransactionStatus::InTransaction(_)
1359            | TransactionStatus::InTransactionImplicit(_)
1360            | TransactionStatus::Failed(_) => false,
1361        }
1362    }
1363
1364    /// Whether the transaction may contain multiple statements.
1365    pub fn is_in_multi_statement_transaction(&self) -> bool {
1366        match self {
1367            TransactionStatus::InTransaction(_) | TransactionStatus::InTransactionImplicit(_) => {
1368                true
1369            }
1370            TransactionStatus::Default
1371            | TransactionStatus::Started(_)
1372            | TransactionStatus::Failed(_) => false,
1373        }
1374    }
1375
1376    /// Whether a statement other than the current one can belong to this
1377    /// transaction, so committing here would commit more than this statement.
1378    ///
1379    /// This is [`Self::is_in_multi_statement_transaction`] widened to cover the
1380    /// `Started` trap. An extended-protocol pipeline stays `Started` from its
1381    /// first statement until `Sync`, so a `Started` transaction already holding
1382    /// ops has a pipeline accumulating in it, and a statement running now runs
1383    /// alongside those ops.
1384    ///
1385    /// Callers must evaluate this before the current statement stages ops of
1386    /// its own. Afterwards `contains_ops` reports the statement's own ops and
1387    /// every statement looks like it shares a transaction.
1388    ///
1389    /// Reports true for a `Failed` transaction that holds ops, since
1390    /// `contains_ops` reads through to the inner transaction in that state.
1391    /// Callers that treat a failed transaction as one a statement may run in
1392    /// need their own check, because pgwire admits only `COMMIT` and `ROLLBACK`
1393    /// once a transaction has failed and so nothing else can observe the
1394    /// difference.
1395    pub fn may_share_transaction_with_other_statements(&self) -> bool {
1396        self.is_in_multi_statement_transaction() || self.contains_ops()
1397    }
1398
1399    /// Whether we are in a multi-statement transaction, AND the query is immediate.
1400    pub fn in_immediate_multi_stmt_txn(&self, when: &QueryWhen) -> bool {
1401        self.is_in_multi_statement_transaction() && when == &QueryWhen::Immediately
1402    }
1403
1404    /// The timeline of the transaction, if one exists.
1405    pub fn timeline(&self) -> Option<Timeline> {
1406        match self {
1407            TransactionStatus::Default => None,
1408            TransactionStatus::Started(txn)
1409            | TransactionStatus::InTransaction(txn)
1410            | TransactionStatus::InTransactionImplicit(txn)
1411            | TransactionStatus::Failed(txn) => txn.timeline(),
1412        }
1413    }
1414
1415    /// The cluster of the transaction, if one exists.
1416    pub fn cluster(&self) -> Option<ClusterId> {
1417        match self {
1418            TransactionStatus::Default => None,
1419            TransactionStatus::Started(txn)
1420            | TransactionStatus::InTransaction(txn)
1421            | TransactionStatus::InTransactionImplicit(txn)
1422            | TransactionStatus::Failed(txn) => txn.cluster(),
1423        }
1424    }
1425
1426    /// Snapshot of the catalog that reflects DDL operations run in this transaction.
1427    pub fn catalog_state(&self) -> Option<&CatalogState> {
1428        match self.inner() {
1429            Some(Transaction {
1430                ops: TransactionOps::DDL { state, .. },
1431                ..
1432            }) => Some(state),
1433            _ => None,
1434        }
1435    }
1436
1437    /// Reports whether any operations have been executed as part of this transaction
1438    pub fn contains_ops(&self) -> bool {
1439        match self.inner() {
1440            Some(txn) => txn.contains_ops(),
1441            None => false,
1442        }
1443    }
1444
1445    /// Checks whether the current state of this transaction allows writes
1446    /// (adding write ops).
1447    pub fn allows_writes(&self) -> bool {
1448        match self {
1449            TransactionStatus::Started(Transaction { ops, access, .. })
1450            | TransactionStatus::InTransaction(Transaction { ops, access, .. })
1451            | TransactionStatus::InTransactionImplicit(Transaction { ops, access, .. }) => {
1452                match ops {
1453                    TransactionOps::None => access != &Some(TransactionAccessMode::ReadOnly),
1454                    TransactionOps::Peeks { determination, .. } => {
1455                        // We can switch a peek-only transaction to a write
1456                        // transaction only if the peeks thus far are constant
1457                        // (i.e. they do not have a timestamp) and the
1458                        // transaction is not explicitly marked read-only.
1459                        access != &Some(TransactionAccessMode::ReadOnly)
1460                            && !determination.timestamp_context.contains_timestamp()
1461                    }
1462                    TransactionOps::Subscribe => false,
1463                    TransactionOps::Writes(_) => true,
1464                    TransactionOps::SingleStatement { .. } => false,
1465                    TransactionOps::DDL { .. } => false,
1466                }
1467            }
1468            TransactionStatus::Default | TransactionStatus::Failed(_) => {
1469                unreachable!()
1470            }
1471        }
1472    }
1473
1474    /// Adds operations to the current transaction. An error is produced if they cannot be merged
1475    /// (i.e., a timestamp-dependent read cannot be merged to an insert).
1476    ///
1477    /// The `DDL` variant is an exception and does not merge operations, but instead overwrites the
1478    /// old ops with the new ops. This is correct because it is only used in conjunction with the
1479    /// Dry Run catalog op which returns an error containing all of the ops, and those ops are
1480    /// passed to this function which then overwrites.
1481    ///
1482    /// # Panics
1483    /// If the operations are compatible but the operation metadata doesn't match. Such as reads at
1484    /// different timestamps, reads on different timelines, reads on different clusters, etc. It's
1485    /// up to the caller to make sure these are aligned.
1486    pub fn add_ops(&mut self, mut add_ops: TransactionOps) -> Result<(), AdapterError> {
1487        if matches!(add_ops, TransactionOps::DDL { .. })
1488            && self.inner().is_some_and(|txn| txn.contains_explain)
1489        {
1490            return Err(AdapterError::DDLOnlyTransaction);
1491        }
1492        match self {
1493            TransactionStatus::Started(Transaction {
1494                ops,
1495                access,
1496                pending_ddl_inspections,
1497                ..
1498            })
1499            | TransactionStatus::InTransaction(Transaction {
1500                ops,
1501                access,
1502                pending_ddl_inspections,
1503                ..
1504            })
1505            | TransactionStatus::InTransactionImplicit(Transaction {
1506                ops,
1507                access,
1508                pending_ddl_inspections,
1509                ..
1510            }) => {
1511                match ops {
1512                    TransactionOps::None => {
1513                        if matches!(access, Some(TransactionAccessMode::ReadOnly))
1514                            && matches!(add_ops, TransactionOps::Writes(_))
1515                        {
1516                            return Err(AdapterError::ReadOnlyTransaction);
1517                        }
1518                        match &mut add_ops {
1519                            TransactionOps::DDL { commands, .. } => {
1520                                // Pre-DDL inspections belong before every mutation, without
1521                                // restricting the transaction until it actually enters DDL mode.
1522                                commands.splice(
1523                                    0..0,
1524                                    pending_ddl_inspections
1525                                        .drain(..)
1526                                        .map(DdlInspection::into_command),
1527                                );
1528                            }
1529                            TransactionOps::None => {}
1530                            TransactionOps::Peeks { .. }
1531                            | TransactionOps::Writes(_)
1532                            | TransactionOps::Subscribe
1533                            | TransactionOps::SingleStatement { .. } => {
1534                                pending_ddl_inspections.clear();
1535                            }
1536                        }
1537                        *ops = add_ops;
1538                    }
1539                    TransactionOps::Peeks {
1540                        determination,
1541                        cluster_id,
1542                        requires_linearization,
1543                    } => match add_ops {
1544                        TransactionOps::Peeks {
1545                            determination: add_timestamp_determination,
1546                            cluster_id: add_cluster_id,
1547                            requires_linearization: add_requires_linearization,
1548                        } => {
1549                            assert_eq!(*cluster_id, add_cluster_id);
1550                            match (
1551                                &determination.timestamp_context,
1552                                &add_timestamp_determination.timestamp_context,
1553                            ) {
1554                                (
1555                                    TimestampContext::TimelineTimestamp {
1556                                        timeline: txn_timeline,
1557                                        chosen_ts: txn_ts,
1558                                        oracle_ts: _,
1559                                    },
1560                                    TimestampContext::TimelineTimestamp {
1561                                        timeline: add_timeline,
1562                                        chosen_ts: add_ts,
1563                                        oracle_ts: _,
1564                                    },
1565                                ) => {
1566                                    assert_eq!(txn_timeline, add_timeline);
1567                                    assert_eq!(txn_ts, add_ts);
1568                                }
1569                                (TimestampContext::NoTimestamp, _) => {
1570                                    *determination = add_timestamp_determination
1571                                }
1572                                (_, TimestampContext::NoTimestamp) => {}
1573                            };
1574                            if matches!(requires_linearization, RequireLinearization::NotRequired)
1575                                && matches!(
1576                                    add_requires_linearization,
1577                                    RequireLinearization::Required
1578                                )
1579                            {
1580                                *requires_linearization = add_requires_linearization;
1581                            }
1582                        }
1583                        // If the peeks thus far are constant (i.e. they do not
1584                        // have a timestamp), writes can follow and switch the
1585                        // transaction to a write transaction. But a read-only
1586                        // transaction must still reject the write. Without that
1587                        // check the write would silently turn a read-only
1588                        // transaction into a write transaction, and a later
1589                        // write would then trip the assert in the `Writes` arm
1590                        // below.
1591                        writes @ TransactionOps::Writes(..)
1592                            if !determination.timestamp_context.contains_timestamp() =>
1593                        {
1594                            if matches!(access, Some(TransactionAccessMode::ReadOnly)) {
1595                                return Err(AdapterError::ReadOnlyTransaction);
1596                            }
1597                            *ops = writes;
1598                        }
1599                        _ => return Err(AdapterError::ReadOnlyTransaction),
1600                    },
1601                    TransactionOps::Subscribe => {
1602                        return Err(AdapterError::SubscribeOnlyTransaction);
1603                    }
1604                    TransactionOps::Writes(txn_writes) => match add_ops {
1605                        TransactionOps::Writes(mut add_writes) => {
1606                            // We should have already checked the access above, but make sure we don't miss
1607                            // it anyway.
1608                            assert!(!matches!(access, Some(TransactionAccessMode::ReadOnly)));
1609                            txn_writes.append(&mut add_writes);
1610                        }
1611                        // Iff peeks do not have a timestamp (i.e. they are
1612                        // constant), we can permit them.
1613                        TransactionOps::Peeks { determination, .. }
1614                            if !determination.timestamp_context.contains_timestamp() => {}
1615                        _ => {
1616                            return Err(AdapterError::WriteOnlyTransaction);
1617                        }
1618                    },
1619                    TransactionOps::SingleStatement { .. } => {
1620                        return Err(AdapterError::SingleStatementTransaction);
1621                    }
1622                    TransactionOps::DDL {
1623                        commands,
1624                        state,
1625                        snapshot,
1626                    } => match add_ops {
1627                        TransactionOps::DDL {
1628                            commands: new_commands,
1629                            state: new_state,
1630                            snapshot: new_snapshot,
1631                        } => {
1632                            if !new_commands.is_empty() {
1633                                commands.extend(new_commands);
1634                                *state = new_state;
1635                                *snapshot = new_snapshot;
1636                            }
1637                        }
1638                        _ => return Err(AdapterError::DDLOnlyTransaction),
1639                    },
1640                }
1641            }
1642            TransactionStatus::Default | TransactionStatus::Failed(_) => {
1643                unreachable!()
1644            }
1645        }
1646        Ok(())
1647    }
1648}
1649
1650/// An abstraction allowing us to identify different transactions.
1651pub type TransactionId = u64;
1652
1653impl Default for TransactionStatus {
1654    fn default() -> Self {
1655        TransactionStatus::Default
1656    }
1657}
1658
1659/// A catalog result or statement description that must remain valid at DDL commit.
1660///
1661/// Retaining inspections before the first DDL statement prevents commit-time
1662/// replanning from contradicting results already exposed or stored for the client.
1663/// Buffering them does not itself enter DDL mode. Transactions that never enter
1664/// DDL mode discard them without validation.
1665#[derive(Debug)]
1666enum DdlInspection {
1667    CatalogResult(Arc<crate::catalog::command::CatalogResultCommand>),
1668    Description(Arc<crate::catalog::command::DescriptionCommand>),
1669}
1670
1671impl DdlInspection {
1672    fn into_command(self) -> crate::catalog::command::CatalogCommand {
1673        match self {
1674            Self::CatalogResult(command) => {
1675                crate::catalog::command::CatalogCommand::CatalogResult(command)
1676            }
1677            Self::Description(command) => {
1678                crate::catalog::command::CatalogCommand::Description(command)
1679            }
1680        }
1681    }
1682}
1683
1684/// State data for transactions.
1685#[derive(Debug)]
1686pub struct Transaction {
1687    completion_owner: TransactionCompletionOwner,
1688    /// Plan context.
1689    pub pcx: PlanContext,
1690    /// Transaction operations.
1691    pub ops: TransactionOps,
1692    /// Catalog results and descriptions awaiting a possible transition to DDL mode.
1693    pending_ddl_inspections: Vec<DdlInspection>,
1694    contains_explain: bool,
1695    /// Uniquely identifies the transaction on a per connection basis.
1696    /// Two transactions started from separate connections may share the
1697    /// same ID.
1698    /// If all IDs have been exhausted, this will wrap around back to 0.
1699    pub id: TransactionId,
1700    /// Access mode (read only, read write).
1701    access: Option<TransactionAccessMode>,
1702}
1703
1704#[derive(Debug, PartialEq)]
1705enum TransactionCompletionOwner {
1706    Session,
1707    Coordinator,
1708}
1709
1710/// Obligations that can be satisfied without transferring the session to the coordinator.
1711pub(crate) struct ReadOnlyCompletion {
1712    pub action: EndTransactionAction,
1713    pub timestamp: Option<TimestampContext>,
1714}
1715
1716impl Transaction {
1717    /// The timeline of the transaction, if one exists.
1718    fn timeline(&self) -> Option<Timeline> {
1719        match &self.ops {
1720            TransactionOps::Peeks {
1721                determination:
1722                    TimestampDetermination {
1723                        timestamp_context: TimestampContext::TimelineTimestamp { timeline, .. },
1724                        ..
1725                    },
1726                ..
1727            } => Some(timeline.clone()),
1728            TransactionOps::Peeks { .. }
1729            | TransactionOps::None
1730            | TransactionOps::Subscribe
1731            | TransactionOps::Writes(_)
1732            | TransactionOps::SingleStatement { .. }
1733            | TransactionOps::DDL { .. } => None,
1734        }
1735    }
1736
1737    /// The cluster of the transaction, if one exists.
1738    pub fn cluster(&self) -> Option<ClusterId> {
1739        match &self.ops {
1740            TransactionOps::Peeks { cluster_id, .. } => Some(cluster_id.clone()),
1741            TransactionOps::None
1742            | TransactionOps::Subscribe
1743            | TransactionOps::Writes(_)
1744            | TransactionOps::SingleStatement { .. }
1745            | TransactionOps::DDL { .. } => None,
1746        }
1747    }
1748
1749    /// Reports whether any operations have been executed as part of this transaction
1750    fn contains_ops(&self) -> bool {
1751        !matches!(self.ops, TransactionOps::None)
1752    }
1753}
1754
1755/// A transaction's status code.
1756#[derive(Debug, Clone, Copy)]
1757pub enum TransactionCode {
1758    /// Not currently in a transaction
1759    Idle,
1760    /// Currently in a transaction
1761    InTransaction,
1762    /// Currently in a transaction block which is failed
1763    Failed,
1764}
1765
1766impl From<TransactionCode> for u8 {
1767    fn from(code: TransactionCode) -> Self {
1768        match code {
1769            TransactionCode::Idle => b'I',
1770            TransactionCode::InTransaction => b'T',
1771            TransactionCode::Failed => b'E',
1772        }
1773    }
1774}
1775
1776impl From<TransactionCode> for String {
1777    fn from(code: TransactionCode) -> Self {
1778        char::from(u8::from(code)).to_string()
1779    }
1780}
1781
1782impl From<&TransactionStatus> for TransactionCode {
1783    /// Convert from the Session's version
1784    fn from(status: &TransactionStatus) -> TransactionCode {
1785        match status {
1786            TransactionStatus::Default => TransactionCode::Idle,
1787            TransactionStatus::Started(_) => TransactionCode::InTransaction,
1788            TransactionStatus::InTransaction(_) => TransactionCode::InTransaction,
1789            TransactionStatus::InTransactionImplicit(_) => TransactionCode::InTransaction,
1790            TransactionStatus::Failed(_) => TransactionCode::Failed,
1791        }
1792    }
1793}
1794
1795/// The type of operation being performed by the transaction.
1796///
1797/// This is needed because we currently do not allow mixing reads and writes in
1798/// a transaction. Use this to record what we have done, and what may need to
1799/// happen at commit.
1800#[derive(Derivative)]
1801#[derivative(Debug)]
1802pub enum TransactionOps {
1803    /// The transaction has been initiated, but no statement has yet been executed
1804    /// in it.
1805    None,
1806    /// This transaction has had a peek (`SELECT`, `SUBSCRIBE`). If the inner value
1807    /// is has a timestamp, it must only do other peeks. However, if it doesn't
1808    /// have a timestamp (i.e. the values are constants), the transaction can still
1809    /// perform writes.
1810    Peeks {
1811        /// The timestamp and timestamp related metadata for the peek.
1812        determination: TimestampDetermination,
1813        /// The cluster used to execute peeks.
1814        cluster_id: ClusterId,
1815        /// Whether this peek needs to be linearized.
1816        requires_linearization: RequireLinearization,
1817    },
1818    /// This transaction has done a `SUBSCRIBE` and must do nothing else.
1819    Subscribe,
1820    /// This transaction has had a write (`INSERT`, `UPDATE`, `DELETE`) and must
1821    /// only do other writes, or reads whose timestamp is None (i.e. constants).
1822    Writes(Vec<WriteOp>),
1823    /// This transaction has a prospective statement that will execute during commit.
1824    SingleStatement {
1825        /// The prospective statement.
1826        stmt: Arc<Statement<Raw>>,
1827        /// The statement params.
1828        params: mz_sql::plan::Params,
1829    },
1830    /// This transaction has run some _simple_ DDL and must do nothing else. Any statement/plan that
1831    /// uses this must return false in `must_serialize_ddl()` because this is serialized instead in
1832    /// `sequence_plan()` during `COMMIT`.
1833    DDL {
1834        /// Commands in statement order, retaining outcomes already exposed to the client.
1835        commands: Vec<crate::catalog::command::CatalogCommand>,
1836        /// Speculative state after the last accepted command.
1837        state: CatalogState,
1838        /// Durable baseline corresponding to `state`.
1839        snapshot: Snapshot,
1840    },
1841}
1842
1843impl TransactionOps {
1844    /// Reports whether the transaction holds work for its commit: writes, DDL that the commit
1845    /// applies, or a statement that runs at commit. A write that affected no rows counts too,
1846    /// because it leaves a `Writes` op behind.
1847    pub fn stages_work(&self) -> bool {
1848        matches!(
1849            self,
1850            TransactionOps::Writes(_)
1851                | TransactionOps::DDL { .. }
1852                | TransactionOps::SingleStatement { .. }
1853        )
1854    }
1855}
1856
1857impl Default for TransactionOps {
1858    fn default() -> Self {
1859        Self::None
1860    }
1861}
1862
1863/// An `INSERT` waiting to be committed.
1864#[derive(Debug, Clone, PartialEq)]
1865pub struct WriteOp {
1866    /// The target table.
1867    pub id: CatalogItemId,
1868    /// The data rows.
1869    pub rows: TableData,
1870}
1871
1872/// Whether a transaction requires linearization.
1873#[derive(Debug)]
1874pub enum RequireLinearization {
1875    /// Linearization is required.
1876    Required,
1877    /// Linearization is not required.
1878    NotRequired,
1879}
1880
1881impl From<&ExplainContext> for RequireLinearization {
1882    fn from(ctx: &ExplainContext) -> Self {
1883        match ctx {
1884            ExplainContext::None | ExplainContext::PlanInsightsNotice(_) => {
1885                RequireLinearization::Required
1886            }
1887            ExplainContext::Plan(_) | ExplainContext::Pushdown | ExplainContext::Timestamp => {
1888                RequireLinearization::NotRequired
1889            }
1890        }
1891    }
1892}
1893#[cfg(test)]
1894mod tests {
1895    use super::*;
1896    use mz_sql::session::vars::{SystemVars, VarInput};
1897    use timely::progress::Antichain;
1898
1899    fn read_session() -> Session {
1900        let mut session = Session::dummy();
1901        session.start_transaction_single_stmt(Utc::now());
1902        session
1903            .add_transaction_ops(TransactionOps::Peeks {
1904                determination: TimestampDetermination {
1905                    timestamp_context: TimestampContext::TimelineTimestamp {
1906                        timeline: Timeline::EpochMilliseconds,
1907                        chosen_ts: 10.into(),
1908                        oracle_ts: Some(10.into()),
1909                    },
1910                    since: Antichain::from_elem(0.into()),
1911                    upper: Antichain::new(),
1912                    largest_not_in_advance_of_upper: Timestamp::MAX,
1913                    oracle_read_ts: Some(10.into()),
1914                    session_oracle_read_ts: None,
1915                    real_time_recency_ts: None,
1916                    constraints: Default::default(),
1917                },
1918                cluster_id: ClusterId::User(1),
1919                requires_linearization: RequireLinearization::Required,
1920            })
1921            .expect("read transaction");
1922        session
1923    }
1924
1925    #[mz_ore::test]
1926    fn read_completion_tracks_ownership_not_just_ops() {
1927        let mut session = read_session();
1928        let completion = session
1929            .read_only_completion(EndTransactionAction::Commit)
1930            .expect("local read");
1931        assert_eq!(completion.action, EndTransactionAction::Commit);
1932        assert!(completion.timestamp.is_some());
1933        session.require_coordinator_completion();
1934        assert!(
1935            session
1936                .read_only_completion(EndTransactionAction::Commit)
1937                .is_none()
1938        );
1939        let _ = session.clear_transaction();
1940        session.start_transaction_single_stmt(Utc::now());
1941        assert!(
1942            session
1943                .read_only_completion(EndTransactionAction::Commit)
1944                .is_some()
1945        );
1946    }
1947
1948    #[mz_ore::test]
1949    fn completion_skips_timestamp_for_failed_and_rolled_back_reads() {
1950        let session = read_session();
1951        let rollback = session
1952            .read_only_completion(EndTransactionAction::Rollback)
1953            .expect("local read");
1954        assert!(rollback.timestamp.is_none());
1955        let session = session.fail_transaction();
1956        let failed = session
1957            .read_only_completion(EndTransactionAction::Commit)
1958            .expect("failed local read");
1959        assert_eq!(failed.action, EndTransactionAction::Rollback);
1960        assert!(failed.timestamp.is_none());
1961    }
1962
1963    #[mz_ore::test]
1964    fn completion_rejects_resource_bearing_transactions() {
1965        for ops in [
1966            TransactionOps::Subscribe,
1967            TransactionOps::Writes(Vec::new()),
1968        ] {
1969            let mut session = Session::dummy();
1970            session.start_transaction_single_stmt(Utc::now());
1971            session.add_transaction_ops(ops).expect("first operation");
1972            assert!(
1973                session
1974                    .read_only_completion(EndTransactionAction::Commit)
1975                    .is_none()
1976            );
1977            assert!(
1978                session
1979                    .fail_transaction()
1980                    .read_only_completion(EndTransactionAction::Rollback)
1981                    .is_none()
1982            );
1983        }
1984    }
1985
1986    #[mz_ore::test]
1987    fn read_completion_preserves_transactional_parameter_changes() {
1988        for action in [EndTransactionAction::Commit, EndTransactionAction::Rollback] {
1989            let mut session = read_session();
1990            session
1991                .vars_mut()
1992                .set_default("application_name", VarInput::Flat("session"))
1993                .expect("default");
1994            session
1995                .vars_mut()
1996                .set(
1997                    &SystemVars::new(),
1998                    "application_name",
1999                    VarInput::Flat("local"),
2000                    true,
2001                )
2002                .expect("local setting");
2003            let completion = session.read_only_completion(action).expect("local read");
2004            let _ = session.clear_transaction();
2005            let params = session.vars_mut().end_transaction(completion.action);
2006            assert_eq!(
2007                params.get("application_name").map(String::as_str),
2008                Some("session")
2009            );
2010            assert_eq!(session.vars().application_name(), "session");
2011            assert!(matches!(session.transaction(), TransactionStatus::Default));
2012        }
2013    }
2014
2015    #[mz_ore::test]
2016    fn ddl_inspections_are_released_when_ddl_becomes_impossible() {
2017        use mz_sql::plan::{Params, StatementDesc};
2018        use timely::progress::Antichain;
2019
2020        let statement = mz_sql_parser::parser::parse_statements("SELECT 1")
2021            .expect("valid SQL")
2022            .remove(0)
2023            .ast;
2024        let modes = [
2025            TransactionOps::Peeks {
2026                determination: TimestampDetermination {
2027                    timestamp_context: TimestampContext::NoTimestamp,
2028                    since: Antichain::new(),
2029                    upper: Antichain::new(),
2030                    largest_not_in_advance_of_upper: mz_repr::Timestamp::MIN,
2031                    oracle_read_ts: None,
2032                    session_oracle_read_ts: None,
2033                    real_time_recency_ts: None,
2034                    constraints: Default::default(),
2035                },
2036                cluster_id: mz_controller_types::ClusterId::User(1),
2037                requires_linearization: RequireLinearization::NotRequired,
2038            },
2039            TransactionOps::Writes(vec![]),
2040            TransactionOps::Subscribe,
2041            TransactionOps::SingleStatement {
2042                stmt: Arc::new(statement.clone()),
2043                params: Params::empty(),
2044            },
2045        ];
2046        // None exercises EXPLAIN, which leaves the operation mode unchanged.
2047        for mode in modes.into_iter().map(Some).chain([None]) {
2048            let mut session = Session::dummy();
2049            session.start_transaction_implicit(Utc::now(), 2);
2050            let command = Arc::new(crate::catalog::command::DescriptionCommand::new(
2051                statement.clone(),
2052                vec![],
2053                session.meta(),
2054                StatementDesc::new(Some(mz_repr::RelationDesc::empty())),
2055            ));
2056            let retained = Arc::downgrade(&command);
2057            session.retain_ddl_inspection(DdlInspection::Description(command));
2058            assert!(retained.upgrade().is_some(), "DDL is still possible");
2059            if let Some(mode) = mode {
2060                session.add_transaction_ops(mode).expect("valid transition");
2061            } else {
2062                session
2063                    .transaction_mut()
2064                    .record_explain()
2065                    .expect("EXPLAIN allowed");
2066            }
2067            assert!(retained.upgrade().is_none(), "release earlier inspections");
2068            let command = Arc::new(crate::catalog::command::DescriptionCommand::new(
2069                statement.clone(),
2070                vec![],
2071                session.meta(),
2072                StatementDesc::new(Some(mz_repr::RelationDesc::empty())),
2073            ));
2074            let discarded = Arc::downgrade(&command);
2075            session.retain_ddl_inspection(DdlInspection::Description(command));
2076            assert!(
2077                discarded.upgrade().is_none(),
2078                "do not retain later inspections"
2079            );
2080        }
2081    }
2082}