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