Skip to main content

risingwave_frontend/
session.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::fmt::{Display, Formatter};
17use std::io::{Error, ErrorKind};
18use std::iter;
19use std::net::{IpAddr, Ipv4Addr, SocketAddr};
20use std::sync::atomic::{AtomicI32, Ordering};
21use std::sync::{Arc, Weak};
22use std::time::{Duration, Instant};
23
24use anyhow::anyhow;
25use bytes::Bytes;
26use either::Either;
27use itertools::Itertools;
28use parking_lot::{Mutex, RwLock, RwLockReadGuard};
29use pgwire::error::{PsqlError, PsqlResult};
30use pgwire::net::{Address, AddressRef};
31use pgwire::pg_field_descriptor::PgFieldDescriptor;
32use pgwire::pg_message::TransactionStatus;
33use pgwire::pg_response::{PgResponse, StatementType};
34use pgwire::pg_server::{
35    BoxedError, ExecContext, ExecContextGuard, Session, SessionId, SessionManager,
36    UserAuthenticator,
37};
38use pgwire::types::{Format, FormatIterator};
39use prometheus_http_query::Client as PrometheusClient;
40use rand::RngCore;
41use risingwave_batch::monitor::{BatchSpillMetrics, GLOBAL_BATCH_SPILL_METRICS};
42use risingwave_batch::spill::spill_op::SpillOp;
43use risingwave_batch::task::{ShutdownSender, ShutdownToken};
44use risingwave_batch::worker_manager::worker_node_manager::{
45    WorkerNodeManager, WorkerNodeManagerRef,
46};
47use risingwave_common::acl::AclMode;
48#[cfg(test)]
49use risingwave_common::catalog::{
50    DEFAULT_DATABASE_NAME, DEFAULT_SUPER_USER, DEFAULT_SUPER_USER_ID,
51};
52use risingwave_common::config::{
53    AuthMethod, BatchConfig, ConnectionType, FrontendConfig, MetaConfig, MetricLevel,
54    RpcClientConfig, StreamingConfig, UdfConfig, load_config,
55};
56use risingwave_common::id::WorkerId;
57use risingwave_common::memory::MemoryContext;
58use risingwave_common::secret::LocalSecretManager;
59use risingwave_common::session_config::{ConfigReporter, SessionConfig, VisibilityMode};
60use risingwave_common::system_param::local_manager::{
61    LocalSystemParamsManager, LocalSystemParamsManagerRef,
62};
63use risingwave_common::telemetry::manager::TelemetryManager;
64use risingwave_common::telemetry::telemetry_env_enabled;
65use risingwave_common::types::DataType;
66use risingwave_common::util::addr::HostAddr;
67use risingwave_common::util::cluster_limit;
68use risingwave_common::util::cluster_limit::ActorCountPerParallelism;
69use risingwave_common::util::iter_util::ZipEqFast;
70use risingwave_common::util::pretty_bytes::convert;
71use risingwave_common::util::runtime::BackgroundShutdownRuntime;
72use risingwave_common::{GIT_SHA, RW_VERSION};
73use risingwave_common_heap_profiling::HeapProfiler;
74use risingwave_common_service::{MetricsManager, ObserverManager};
75use risingwave_connector::source::monitor::{GLOBAL_SOURCE_METRICS, SourceMetrics};
76use risingwave_pb::common::WorkerType;
77use risingwave_pb::common::worker_node::Property as AddWorkerNodeProperty;
78use risingwave_pb::configured_monitor_service_server;
79use risingwave_pb::frontend_service::frontend_service_server::FrontendServiceServer;
80use risingwave_pb::health::health_server::HealthServer;
81use risingwave_pb::monitor_service::monitor_service_server::MonitorServiceServer;
82use risingwave_pb::user::auth_info::EncryptionType;
83use risingwave_rpc_client::{
84    ComputeClientPool, ComputeClientPoolRef, FrontendClientPool, FrontendClientPoolRef, MetaClient,
85    MonitorClientPool, MonitorClientPoolRef,
86};
87use risingwave_sqlparser::ast::{ObjectName, Statement};
88use risingwave_sqlparser::parser::Parser;
89use thiserror::Error;
90use thiserror_ext::AsReport;
91use tokio::runtime::Builder;
92use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
93use tokio::sync::oneshot::Sender;
94use tokio::sync::watch;
95use tokio::task::JoinHandle;
96use tracing::{error, info};
97
98use self::cursor_manager::CursorManager;
99use crate::binder::{Binder, BoundStatement, ResolveQualifiedNameError};
100use crate::catalog::catalog_service::{CatalogReader, CatalogWriter, CatalogWriterImpl};
101use crate::catalog::connection_catalog::ConnectionCatalog;
102use crate::catalog::root_catalog::{Catalog, SchemaPath};
103use crate::catalog::secret_catalog::SecretCatalog;
104use crate::catalog::source_catalog::SourceCatalog;
105use crate::catalog::subscription_catalog::SubscriptionCatalog;
106use crate::catalog::{
107    CatalogError, CatalogErrorInner, DatabaseId, OwnedByUserCatalog, SchemaId, TableId,
108    check_schema_writable,
109};
110use crate::error::{
111    ErrorCode, Result, RwError, bail_catalog_error, bail_permission_denied, bail_protocol_error,
112};
113use crate::handler::describe::infer_describe;
114use crate::handler::extended_handle::{
115    Portal, PrepareStatement, handle_bind, handle_execute, handle_parse,
116};
117use crate::handler::privilege::ObjectCheckItem;
118use crate::handler::show::{infer_show_create_object, infer_show_object};
119use crate::handler::util::to_pg_field;
120use crate::handler::variable::infer_show_variable;
121use crate::handler::{RwPgResponse, handle};
122use crate::health_service::HealthServiceImpl;
123use crate::meta_client::{FrontendMetaClient, FrontendMetaClientImpl};
124use crate::monitor::{CursorMetrics, FrontendMetrics, GLOBAL_FRONTEND_METRICS};
125use crate::observer::FrontendObserverNode;
126use crate::rpc::{FrontendServiceImpl, MonitorServiceImpl};
127use crate::scheduler::streaming_manager::{StreamingJobTracker, StreamingJobTrackerRef};
128use crate::scheduler::{
129    DistributedQueryMetrics, GLOBAL_DISTRIBUTED_QUERY_METRICS, HummockSnapshotManager,
130    HummockSnapshotManagerRef, QueryManager,
131};
132use crate::telemetry::FrontendTelemetryCreator;
133use crate::user::UserId;
134use crate::user::user_authentication::md5_hash_with_salt;
135use crate::user::user_manager::UserInfoManager;
136use crate::user::user_service::{UserInfoReader, UserInfoWriter, UserInfoWriterImpl};
137use crate::{FrontendOpts, PgResponseStream, TableCatalog};
138
139pub(crate) mod current;
140pub(crate) mod cursor_manager;
141pub(crate) mod transaction;
142
143/// The global environment for the frontend server.
144#[derive(Clone)]
145pub(crate) struct FrontendEnv {
146    // Different session may access catalog at the same time and catalog is protected by a
147    // RwLock.
148    meta_client: Arc<dyn FrontendMetaClient>,
149    catalog_writer: Arc<dyn CatalogWriter>,
150    catalog_reader: CatalogReader,
151    user_info_writer: Arc<dyn UserInfoWriter>,
152    user_info_reader: UserInfoReader,
153    worker_node_manager: WorkerNodeManagerRef,
154    query_manager: QueryManager,
155    hummock_snapshot_manager: HummockSnapshotManagerRef,
156    system_params_manager: LocalSystemParamsManagerRef,
157    session_params: Arc<RwLock<SessionConfig>>,
158
159    server_addr: HostAddr,
160    client_pool: ComputeClientPoolRef,
161    frontend_client_pool: FrontendClientPoolRef,
162    monitor_client_pool: MonitorClientPoolRef,
163
164    /// Each session is identified by (`process_id`,
165    /// `secret_key`). When Cancel Request received, find corresponding session and cancel all
166    /// running queries.
167    sessions_map: SessionMapRef,
168
169    pub frontend_metrics: Arc<FrontendMetrics>,
170
171    pub cursor_metrics: Arc<CursorMetrics>,
172
173    source_metrics: Arc<SourceMetrics>,
174
175    /// Batch spill metrics
176    spill_metrics: Arc<BatchSpillMetrics>,
177
178    batch_config: BatchConfig,
179    frontend_config: FrontendConfig,
180    #[expect(dead_code)]
181    meta_config: MetaConfig,
182    streaming_config: StreamingConfig,
183    udf_config: UdfConfig,
184
185    /// Track creating streaming jobs, used to cancel creating streaming job when cancel request
186    /// received.
187    creating_streaming_job_tracker: StreamingJobTrackerRef,
188
189    /// Runtime for compute intensive tasks in frontend, e.g. executors in local mode,
190    /// root stage in mpp mode.
191    compute_runtime: Arc<BackgroundShutdownRuntime>,
192
193    /// Memory context used for batch executors in frontend.
194    mem_context: MemoryContext,
195
196    #[cfg(feature = "datafusion")]
197    /// Shared budget context for **DataFusion** spillable operators.
198    /// Created by [`crate::datafusion::execute::memory_ctx::create_df_spillable_budget_ctx`];
199    /// caps total spillable usage so unspillable operators always have headroom.
200    /// Not used by the RisingWave batch engine.
201    df_spillable_budget_ctx: MemoryContext,
202
203    /// Prometheus client for querying metrics.
204    prometheus_client: Option<PrometheusClient>,
205
206    /// The additional selector used when querying Prometheus.
207    prometheus_selector: String,
208}
209
210/// Session map identified by `(process_id, secret_key)`
211pub type SessionMapRef = Arc<RwLock<HashMap<(i32, i32), Arc<SessionImpl>>>>;
212
213/// The proportion of frontend memory used for batch processing.
214const FRONTEND_BATCH_MEMORY_PROPORTION: f64 = 0.5;
215
216impl FrontendEnv {
217    pub fn mock() -> Self {
218        use crate::test_utils::{MockCatalogWriter, MockFrontendMetaClient, MockUserInfoWriter};
219
220        let catalog = Arc::new(RwLock::new(Catalog::default()));
221        let meta_client = Arc::new(MockFrontendMetaClient {});
222        let hummock_snapshot_manager = Arc::new(HummockSnapshotManager::new(meta_client.clone()));
223        let catalog_writer = Arc::new(MockCatalogWriter::new(
224            catalog.clone(),
225            hummock_snapshot_manager.clone(),
226        ));
227        let catalog_reader = CatalogReader::new(catalog);
228        let user_info_manager = Arc::new(RwLock::new(UserInfoManager::default()));
229        let user_info_writer = Arc::new(MockUserInfoWriter::new(user_info_manager.clone()));
230        let user_info_reader = UserInfoReader::new(user_info_manager);
231        let worker_node_manager = Arc::new(WorkerNodeManager::mock(vec![]));
232        let system_params_manager = Arc::new(LocalSystemParamsManager::for_test());
233        let compute_client_pool = Arc::new(ComputeClientPool::for_test());
234        let frontend_client_pool = Arc::new(FrontendClientPool::for_test());
235        let monitor_client_pool = Arc::new(MonitorClientPool::for_test());
236        let query_manager = QueryManager::new(
237            worker_node_manager.clone(),
238            compute_client_pool,
239            catalog_reader.clone(),
240            Arc::new(DistributedQueryMetrics::for_test()),
241            None,
242            None,
243        );
244        let server_addr = HostAddr::try_from("127.0.0.1:4565").unwrap();
245        let client_pool = Arc::new(ComputeClientPool::for_test());
246        let creating_streaming_tracker = StreamingJobTracker::new(meta_client.clone());
247        let runtime = {
248            let mut builder = Builder::new_multi_thread();
249            if let Some(frontend_compute_runtime_worker_threads) =
250                load_config("", FrontendOpts::default())
251                    .batch
252                    .frontend_compute_runtime_worker_threads
253            {
254                builder.worker_threads(frontend_compute_runtime_worker_threads);
255            }
256            builder
257                .thread_name("rw-batch-local")
258                .enable_all()
259                .build()
260                .unwrap()
261        };
262        let compute_runtime = Arc::new(BackgroundShutdownRuntime::from(runtime));
263        let sessions_map = Arc::new(RwLock::new(HashMap::new()));
264        Self {
265            meta_client,
266            catalog_writer,
267            catalog_reader,
268            user_info_writer,
269            user_info_reader,
270            worker_node_manager,
271            query_manager,
272            hummock_snapshot_manager,
273            system_params_manager,
274            session_params: Default::default(),
275            server_addr,
276            client_pool,
277            frontend_client_pool,
278            monitor_client_pool,
279            sessions_map,
280            frontend_metrics: Arc::new(FrontendMetrics::for_test()),
281            cursor_metrics: Arc::new(CursorMetrics::for_test()),
282            batch_config: BatchConfig::default(),
283            frontend_config: FrontendConfig::default(),
284            meta_config: MetaConfig::default(),
285            streaming_config: StreamingConfig::default(),
286            udf_config: UdfConfig::default(),
287            source_metrics: Arc::new(SourceMetrics::default()),
288            spill_metrics: BatchSpillMetrics::for_test(),
289            creating_streaming_job_tracker: Arc::new(creating_streaming_tracker),
290            compute_runtime,
291            mem_context: MemoryContext::none(),
292            #[cfg(feature = "datafusion")]
293            df_spillable_budget_ctx: MemoryContext::none(),
294            prometheus_client: None,
295            prometheus_selector: String::new(),
296        }
297    }
298
299    pub(crate) fn set_frontend_config_for_test(&mut self, frontend_config: FrontendConfig) {
300        self.frontend_config = frontend_config;
301    }
302
303    pub async fn init(opts: FrontendOpts) -> Result<(Self, Vec<JoinHandle<()>>, Vec<Sender<()>>)> {
304        let config = load_config(&opts.config_path, &opts);
305        info!("Starting frontend node");
306        info!("> config: {:?}", config);
307        info!(
308            "> debug assertions: {}",
309            if cfg!(debug_assertions) { "on" } else { "off" }
310        );
311        info!("> version: {} ({})", RW_VERSION, GIT_SHA);
312
313        let frontend_address: HostAddr = opts
314            .advertise_addr
315            .as_ref()
316            .unwrap_or_else(|| {
317                tracing::warn!("advertise address is not specified; defaulting to listen_addr");
318                &opts.listen_addr
319            })
320            .parse()
321            .unwrap();
322        info!("advertise address is {}", frontend_address);
323
324        let rpc_addr: HostAddr = opts.frontend_rpc_listener_addr.parse().unwrap();
325        let internal_rpc_host_addr = HostAddr {
326            // Use the host of advertise address for the frontend rpc address.
327            host: frontend_address.host.clone(),
328            port: rpc_addr.port,
329        };
330        // Register in meta by calling `AddWorkerNode` RPC.
331        let (meta_client, system_params_reader) = MetaClient::register_new(
332            opts.meta_addr,
333            WorkerType::Frontend,
334            &frontend_address,
335            AddWorkerNodeProperty {
336                internal_rpc_host_addr: internal_rpc_host_addr.to_string(),
337                ..Default::default()
338            },
339            Arc::new(config.meta.clone()),
340        )
341        .await;
342
343        let worker_id = meta_client.worker_id();
344        info!("Assigned worker node id {}", worker_id);
345
346        let (heartbeat_join_handle, heartbeat_shutdown_sender) = MetaClient::start_heartbeat_loop(
347            meta_client.clone(),
348            Duration::from_millis(config.server.heartbeat_interval_ms as u64),
349        );
350        let mut join_handles = vec![heartbeat_join_handle];
351        let mut shutdown_senders = vec![heartbeat_shutdown_sender];
352
353        let frontend_meta_client = Arc::new(FrontendMetaClientImpl(meta_client.clone()));
354        let hummock_snapshot_manager =
355            Arc::new(HummockSnapshotManager::new(frontend_meta_client.clone()));
356
357        let (catalog_updated_tx, catalog_updated_rx) = watch::channel(0);
358        let catalog = Arc::new(RwLock::new(Catalog::default()));
359        let catalog_writer = Arc::new(CatalogWriterImpl::new(
360            meta_client.clone(),
361            catalog_updated_rx.clone(),
362            hummock_snapshot_manager.clone(),
363        ));
364        let catalog_reader = CatalogReader::new(catalog.clone());
365
366        let worker_node_manager = Arc::new(WorkerNodeManager::new());
367
368        let compute_client_pool = Arc::new(ComputeClientPool::new(
369            config.batch_exchange_connection_pool_size(),
370            config.batch.developer.compute_client_config.clone(),
371        ));
372        let frontend_client_pool = Arc::new(FrontendClientPool::new(
373            1,
374            config.batch.developer.frontend_client_config.clone(),
375        ));
376        let monitor_client_pool = Arc::new(MonitorClientPool::new(1, RpcClientConfig::default()));
377        let query_manager = QueryManager::new(
378            worker_node_manager.clone(),
379            compute_client_pool.clone(),
380            catalog_reader.clone(),
381            Arc::new(GLOBAL_DISTRIBUTED_QUERY_METRICS.clone()),
382            config.batch.distributed_query_limit,
383            config.batch.max_batch_queries_per_frontend_node,
384        );
385
386        let user_info_manager = Arc::new(RwLock::new(UserInfoManager::default()));
387        let user_info_reader = UserInfoReader::new(user_info_manager.clone());
388        let user_info_writer = Arc::new(UserInfoWriterImpl::new(
389            meta_client.clone(),
390            catalog_updated_rx,
391        ));
392
393        let system_params_manager =
394            Arc::new(LocalSystemParamsManager::new(system_params_reader.clone()));
395
396        LocalSecretManager::init(
397            opts.temp_secret_file_dir,
398            meta_client.cluster_id().to_owned(),
399            worker_id,
400        );
401
402        // This `session_params` should be initialized during the initial notification in `observer_manager`
403        let session_params = Arc::new(RwLock::new(SessionConfig::default()));
404        let sessions_map: SessionMapRef = Arc::new(RwLock::new(HashMap::new()));
405        let cursor_metrics = Arc::new(CursorMetrics::init(sessions_map.clone()));
406
407        let frontend_observer_node = FrontendObserverNode::new(
408            worker_node_manager.clone(),
409            catalog,
410            catalog_updated_tx,
411            user_info_manager,
412            hummock_snapshot_manager.clone(),
413            system_params_manager.clone(),
414            session_params.clone(),
415            compute_client_pool.clone(),
416        );
417        let observer_manager =
418            ObserverManager::new_with_meta_client(meta_client.clone(), frontend_observer_node)
419                .await;
420        let observer_join_handle = observer_manager.start().await;
421        join_handles.push(observer_join_handle);
422
423        meta_client.activate(&frontend_address).await?;
424
425        let frontend_metrics = Arc::new(GLOBAL_FRONTEND_METRICS.clone());
426        risingwave_connector::init_connector_metrics(config.server.metrics_level);
427        let source_metrics = Arc::new(GLOBAL_SOURCE_METRICS.clone());
428        let spill_metrics = Arc::new(GLOBAL_BATCH_SPILL_METRICS.clone());
429
430        if config.server.metrics_level > MetricLevel::Disabled {
431            MetricsManager::boot_metrics_service(opts.prometheus_listener_addr.clone());
432        }
433
434        let health_srv = HealthServiceImpl::new();
435        let frontend_srv = FrontendServiceImpl::new(sessions_map.clone());
436        let monitor_srv = MonitorServiceImpl::new(config.server.clone());
437        let frontend_rpc_addr = opts.frontend_rpc_listener_addr.parse().unwrap();
438
439        let telemetry_manager = TelemetryManager::new(
440            Arc::new(meta_client.clone()),
441            Arc::new(FrontendTelemetryCreator::new()),
442        );
443
444        // if the toml config file or env variable disables telemetry, do not watch system params
445        // change because if any of configs disable telemetry, we should never start it
446        if config.server.telemetry_enabled && telemetry_env_enabled() {
447            let (join_handle, shutdown_sender) = telemetry_manager.start().await;
448            join_handles.push(join_handle);
449            shutdown_senders.push(shutdown_sender);
450        } else {
451            tracing::info!("Telemetry did not start because it is disabled by configuration");
452        }
453
454        tokio::spawn(async move {
455            tonic::transport::Server::builder()
456                .add_service(HealthServer::new(health_srv))
457                .add_service(FrontendServiceServer::new(frontend_srv))
458                .add_service(configured_monitor_service_server(
459                    MonitorServiceServer::new(monitor_srv),
460                ))
461                .serve(frontend_rpc_addr)
462                .await
463                .unwrap();
464        });
465        info!(
466            "Health check RPC listener is listening on {}",
467            opts.frontend_rpc_listener_addr.clone()
468        );
469
470        let creating_streaming_job_tracker =
471            Arc::new(StreamingJobTracker::new(frontend_meta_client.clone()));
472
473        let runtime = {
474            let mut builder = Builder::new_multi_thread();
475            if let Some(frontend_compute_runtime_worker_threads) =
476                config.batch.frontend_compute_runtime_worker_threads
477            {
478                builder.worker_threads(frontend_compute_runtime_worker_threads);
479            }
480            builder
481                .thread_name("rw-batch-local")
482                .enable_all()
483                .build()
484                .unwrap()
485        };
486        let compute_runtime = Arc::new(BackgroundShutdownRuntime::from(runtime));
487
488        let sessions = sessions_map.clone();
489        // Idle transaction background monitor
490        let join_handle = tokio::spawn(async move {
491            let mut check_idle_txn_interval =
492                tokio::time::interval(core::time::Duration::from_secs(10));
493            check_idle_txn_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
494            check_idle_txn_interval.reset();
495            loop {
496                check_idle_txn_interval.tick().await;
497                sessions.read().values().for_each(|session| {
498                    let _ = session.check_idle_in_transaction_timeout();
499                })
500            }
501        });
502        join_handles.push(join_handle);
503
504        // Clean up the spill directory.
505        #[cfg(not(madsim))]
506        if config.batch.enable_spill {
507            SpillOp::clean_spill_directory()
508                .await
509                .map_err(|err| anyhow!(err))?;
510        }
511
512        let total_memory_bytes = opts.frontend_total_memory_bytes;
513        let heap_profiler =
514            HeapProfiler::new(total_memory_bytes, config.server.heap_profiling.clone());
515        // Run a background heap profiler
516        heap_profiler.start();
517
518        let batch_memory_limit = total_memory_bytes as f64 * FRONTEND_BATCH_MEMORY_PROPORTION;
519        let mem_context = MemoryContext::root(
520            frontend_metrics.batch_total_mem.clone(),
521            batch_memory_limit as u64,
522        );
523        #[cfg(feature = "datafusion")]
524        let df_spillable_budget_ctx =
525            crate::datafusion::create_df_spillable_budget_ctx(&mem_context);
526
527        // Initialize Prometheus client if endpoint is provided
528        let prometheus_client = if let Some(ref endpoint) = opts.prometheus_endpoint {
529            match PrometheusClient::try_from(endpoint.as_str()) {
530                Ok(client) => {
531                    info!("Prometheus client initialized with endpoint: {}", endpoint);
532                    Some(client)
533                }
534                Err(e) => {
535                    error!(
536                        error = %e.as_report(),
537                        "failed to initialize Prometheus client",
538                    );
539                    None
540                }
541            }
542        } else {
543            None
544        };
545
546        // Initialize Prometheus selector
547        let prometheus_selector = opts.prometheus_selector.unwrap_or_default();
548
549        info!(
550            "Frontend total memory: {}, batch memory: {}",
551            convert(total_memory_bytes as _),
552            convert(batch_memory_limit as _),
553        );
554
555        Ok((
556            Self {
557                catalog_reader,
558                catalog_writer,
559                user_info_reader,
560                user_info_writer,
561                worker_node_manager,
562                meta_client: frontend_meta_client,
563                query_manager,
564                hummock_snapshot_manager,
565                system_params_manager,
566                session_params,
567                server_addr: frontend_address,
568                client_pool: compute_client_pool,
569                frontend_client_pool,
570                monitor_client_pool,
571                frontend_metrics,
572                cursor_metrics,
573                spill_metrics,
574                sessions_map,
575                batch_config: config.batch,
576                frontend_config: config.frontend,
577                meta_config: config.meta,
578                streaming_config: config.streaming,
579                udf_config: config.udf,
580                source_metrics,
581                creating_streaming_job_tracker,
582                compute_runtime,
583                mem_context,
584                #[cfg(feature = "datafusion")]
585                df_spillable_budget_ctx,
586                prometheus_client,
587                prometheus_selector,
588            },
589            join_handles,
590            shutdown_senders,
591        ))
592    }
593
594    /// Get a reference to the frontend env's catalog writer.
595    ///
596    /// This method is intentionally private, and a write guard is required for the caller to
597    /// prove that the write operations are permitted in the current transaction.
598    fn catalog_writer(&self, _guard: transaction::WriteGuard) -> &dyn CatalogWriter {
599        &*self.catalog_writer
600    }
601
602    /// Get a reference to the frontend env's catalog reader.
603    pub fn catalog_reader(&self) -> &CatalogReader {
604        &self.catalog_reader
605    }
606
607    /// Get a reference to the frontend env's user info writer.
608    ///
609    /// This method is intentionally private, and a write guard is required for the caller to
610    /// prove that the write operations are permitted in the current transaction.
611    fn user_info_writer(&self, _guard: transaction::WriteGuard) -> &dyn UserInfoWriter {
612        &*self.user_info_writer
613    }
614
615    /// Get a reference to the frontend env's user info reader.
616    pub fn user_info_reader(&self) -> &UserInfoReader {
617        &self.user_info_reader
618    }
619
620    pub fn worker_node_manager_ref(&self) -> WorkerNodeManagerRef {
621        self.worker_node_manager.clone()
622    }
623
624    pub fn meta_client(&self) -> &dyn FrontendMetaClient {
625        &*self.meta_client
626    }
627
628    pub fn meta_client_ref(&self) -> Arc<dyn FrontendMetaClient> {
629        self.meta_client.clone()
630    }
631
632    pub fn query_manager(&self) -> &QueryManager {
633        &self.query_manager
634    }
635
636    pub fn hummock_snapshot_manager(&self) -> &HummockSnapshotManagerRef {
637        &self.hummock_snapshot_manager
638    }
639
640    pub fn system_params_manager(&self) -> &LocalSystemParamsManagerRef {
641        &self.system_params_manager
642    }
643
644    pub fn session_params_snapshot(&self) -> SessionConfig {
645        self.session_params.read_recursive().clone()
646    }
647
648    /// Get a reference to the Prometheus client if available.
649    pub fn prometheus_client(&self) -> Option<&PrometheusClient> {
650        self.prometheus_client.as_ref()
651    }
652
653    /// Get the Prometheus selector string.
654    pub fn prometheus_selector(&self) -> &str {
655        &self.prometheus_selector
656    }
657
658    pub fn server_address(&self) -> &HostAddr {
659        &self.server_addr
660    }
661
662    pub fn client_pool(&self) -> ComputeClientPoolRef {
663        self.client_pool.clone()
664    }
665
666    pub fn frontend_client_pool(&self) -> FrontendClientPoolRef {
667        self.frontend_client_pool.clone()
668    }
669
670    pub fn monitor_client_pool(&self) -> MonitorClientPoolRef {
671        self.monitor_client_pool.clone()
672    }
673
674    pub fn batch_config(&self) -> &BatchConfig {
675        &self.batch_config
676    }
677
678    pub fn frontend_config(&self) -> &FrontendConfig {
679        &self.frontend_config
680    }
681
682    pub fn streaming_config(&self) -> &StreamingConfig {
683        &self.streaming_config
684    }
685
686    pub fn udf_config(&self) -> &UdfConfig {
687        &self.udf_config
688    }
689
690    pub fn source_metrics(&self) -> Arc<SourceMetrics> {
691        self.source_metrics.clone()
692    }
693
694    pub fn spill_metrics(&self) -> Arc<BatchSpillMetrics> {
695        self.spill_metrics.clone()
696    }
697
698    pub fn creating_streaming_job_tracker(&self) -> &StreamingJobTrackerRef {
699        &self.creating_streaming_job_tracker
700    }
701
702    pub fn sessions_map(&self) -> &SessionMapRef {
703        &self.sessions_map
704    }
705
706    pub fn compute_runtime(&self) -> Arc<BackgroundShutdownRuntime> {
707        self.compute_runtime.clone()
708    }
709
710    /// Cancel queries (i.e. batch queries) in session.
711    /// If the session exists return true, otherwise, return false.
712    pub fn cancel_queries_in_session(&self, session_id: SessionId) -> bool {
713        cancel_queries_in_session(session_id, self.sessions_map.clone())
714    }
715
716    /// Cancel creating jobs (i.e. streaming queries) in session.
717    /// If the session exists return true, otherwise, return false.
718    pub fn cancel_creating_jobs_in_session(&self, session_id: SessionId) -> bool {
719        cancel_creating_jobs_in_session(session_id, self.sessions_map.clone())
720    }
721
722    pub fn mem_context(&self) -> MemoryContext {
723        self.mem_context.clone()
724    }
725
726    #[cfg(feature = "datafusion")]
727    pub fn df_spillable_budget_ctx(&self) -> MemoryContext {
728        self.df_spillable_budget_ctx.clone()
729    }
730}
731
732#[derive(Clone)]
733pub struct AuthContext {
734    pub database: String,
735    pub user_name: String,
736    pub user_id: UserId,
737}
738
739impl AuthContext {
740    pub fn new(database: String, user_name: String, user_id: UserId) -> Self {
741        Self {
742            database,
743            user_name,
744            user_id,
745        }
746    }
747}
748pub struct SessionImpl {
749    env: FrontendEnv,
750    auth_context: Arc<RwLock<AuthContext>>,
751    /// Used for user authentication.
752    user_authenticator: UserAuthenticator,
753    /// Stores the value of configurations.
754    config_map: Arc<RwLock<SessionConfig>>,
755
756    /// Channel sender for frontend handler to send notices.
757    notice_tx: UnboundedSender<String>,
758    /// Channel receiver for pgwire to take notices and send to clients.
759    notice_rx: Mutex<UnboundedReceiver<String>>,
760
761    /// Identified by `process_id`, `secret_key`. Corresponds to `SessionManager`.
762    id: (i32, i32),
763
764    /// Client address
765    peer_addr: AddressRef,
766
767    /// Transaction state.
768    /// TODO: get rid of the `Mutex` here as a workaround if the `Send` requirement of
769    /// async functions, there should actually be no contention.
770    txn: Arc<Mutex<transaction::State>>,
771
772    /// Query cancel flag.
773    /// This flag is set only when current query is executed in local mode, and used to cancel
774    /// local query.
775    current_query_cancel_flag: Mutex<Option<ShutdownSender>>,
776
777    /// execution context represents the lifetime of a running SQL in the current session
778    exec_context: Mutex<Option<Weak<ExecContext>>>,
779
780    /// Last idle instant
781    last_idle_instant: Arc<Mutex<Option<Instant>>>,
782
783    cursor_manager: Arc<CursorManager>,
784
785    /// temporary sources for the current session
786    temporary_source_manager: Arc<Mutex<TemporarySourceManager>>,
787
788    /// staging catalogs for the current session
789    staging_catalog_manager: Arc<Mutex<StagingCatalogManager>>,
790}
791
792/// If TEMPORARY or TEMP is specified, the source is created as a temporary source.
793/// Temporary sources are automatically dropped at the end of a session
794/// Temporary sources are expected to be selected by batch queries, not streaming queries.
795/// Temporary sources currently are only used by cloud portal to preview the data during table and
796/// source creation, so it is a internal feature and not exposed to users.
797/// The current PR supports temporary source with minimum effort,
798/// so we don't care about the database name and schema name, but only care about the source name.
799/// Temporary sources can only be shown via `show sources` command but not other system tables.
800#[derive(Default, Clone)]
801pub struct TemporarySourceManager {
802    sources: HashMap<String, SourceCatalog>,
803}
804
805impl TemporarySourceManager {
806    pub fn new() -> Self {
807        Self {
808            sources: HashMap::new(),
809        }
810    }
811
812    pub fn create_source(&mut self, name: String, source: SourceCatalog) {
813        self.sources.insert(name, source);
814    }
815
816    pub fn drop_source(&mut self, name: &str) {
817        self.sources.remove(name);
818    }
819
820    pub fn get_source(&self, name: &str) -> Option<&SourceCatalog> {
821        self.sources.get(name)
822    }
823
824    pub fn keys(&self) -> Vec<String> {
825        self.sources.keys().cloned().collect()
826    }
827}
828
829/// Staging catalog manager is used to manage the tables creating in the current session.
830#[derive(Default, Clone)]
831pub struct StagingCatalogManager {
832    // staging tables creating in the current session.
833    tables: HashMap<String, TableCatalog>,
834}
835
836impl StagingCatalogManager {
837    pub fn new() -> Self {
838        Self {
839            tables: HashMap::new(),
840        }
841    }
842
843    pub fn create_table(&mut self, name: String, table: TableCatalog) {
844        self.tables.insert(name, table);
845    }
846
847    pub fn drop_table(&mut self, name: &str) {
848        self.tables.remove(name);
849    }
850
851    pub fn get_table(&self, name: &str) -> Option<&TableCatalog> {
852        self.tables.get(name)
853    }
854}
855
856#[derive(Error, Debug)]
857pub enum CheckRelationError {
858    #[error("{0}")]
859    Resolve(#[from] ResolveQualifiedNameError),
860    #[error("{0}")]
861    Catalog(#[from] CatalogError),
862}
863
864impl From<CheckRelationError> for RwError {
865    fn from(e: CheckRelationError) -> Self {
866        match e {
867            CheckRelationError::Resolve(e) => e.into(),
868            CheckRelationError::Catalog(e) => e.into(),
869        }
870    }
871}
872
873impl SessionImpl {
874    pub(crate) fn new(
875        env: FrontendEnv,
876        auth_context: AuthContext,
877        user_authenticator: UserAuthenticator,
878        id: SessionId,
879        peer_addr: AddressRef,
880        session_config: SessionConfig,
881    ) -> Self {
882        let cursor_metrics = env.cursor_metrics.clone();
883        let (notice_tx, notice_rx) = mpsc::unbounded_channel();
884
885        Self {
886            env,
887            auth_context: Arc::new(RwLock::new(auth_context)),
888            user_authenticator,
889            config_map: Arc::new(RwLock::new(session_config)),
890            id,
891            peer_addr,
892            txn: Default::default(),
893            current_query_cancel_flag: Mutex::new(None),
894            notice_tx,
895            notice_rx: Mutex::new(notice_rx),
896            exec_context: Mutex::new(None),
897            last_idle_instant: Default::default(),
898            cursor_manager: Arc::new(CursorManager::new(cursor_metrics)),
899            temporary_source_manager: Default::default(),
900            staging_catalog_manager: Default::default(),
901        }
902    }
903
904    #[cfg(test)]
905    pub fn mock() -> Self {
906        let env = FrontendEnv::mock();
907        let (notice_tx, notice_rx) = mpsc::unbounded_channel();
908
909        Self {
910            env: FrontendEnv::mock(),
911            auth_context: Arc::new(RwLock::new(AuthContext::new(
912                DEFAULT_DATABASE_NAME.to_owned(),
913                DEFAULT_SUPER_USER.to_owned(),
914                DEFAULT_SUPER_USER_ID,
915            ))),
916            user_authenticator: UserAuthenticator::None,
917            config_map: Default::default(),
918            // Mock session use non-sense id.
919            id: (0, 0),
920            txn: Default::default(),
921            current_query_cancel_flag: Mutex::new(None),
922            notice_tx,
923            notice_rx: Mutex::new(notice_rx),
924            exec_context: Mutex::new(None),
925            peer_addr: Address::Tcp(SocketAddr::new(
926                IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
927                8080,
928            ))
929            .into(),
930            last_idle_instant: Default::default(),
931            cursor_manager: Arc::new(CursorManager::new(env.cursor_metrics)),
932            temporary_source_manager: Default::default(),
933            staging_catalog_manager: Default::default(),
934        }
935    }
936
937    pub(crate) fn env(&self) -> &FrontendEnv {
938        &self.env
939    }
940
941    pub fn auth_context(&self) -> Arc<AuthContext> {
942        let ctx = self.auth_context.read();
943        Arc::new(ctx.clone())
944    }
945
946    pub fn database(&self) -> String {
947        self.auth_context.read().database.clone()
948    }
949
950    pub fn database_id(&self) -> DatabaseId {
951        let db_name = self.database();
952        self.env
953            .catalog_reader()
954            .read_guard()
955            .get_database_by_name(&db_name)
956            .map(|db| db.id())
957            .expect("session database not found")
958    }
959
960    pub fn user_name(&self) -> String {
961        self.auth_context.read().user_name.clone()
962    }
963
964    pub fn user_id(&self) -> UserId {
965        self.auth_context.read().user_id
966    }
967
968    pub fn update_database(&self, database: String) {
969        self.auth_context.write().database = database;
970    }
971
972    pub fn shared_config(&self) -> Arc<RwLock<SessionConfig>> {
973        Arc::clone(&self.config_map)
974    }
975
976    pub fn config(&self) -> RwLockReadGuard<'_, SessionConfig> {
977        self.config_map.read()
978    }
979
980    pub fn set_config(&self, key: &str, value: String) -> Result<String> {
981        self.config_map
982            .write()
983            .set(key, value, &mut ())
984            .map_err(Into::into)
985    }
986
987    pub fn reset_config(&self, key: &str) -> Result<String> {
988        self.config_map
989            .write()
990            .reset(key, &mut ())
991            .map_err(Into::into)
992    }
993
994    pub fn set_config_report(
995        &self,
996        key: &str,
997        value: Option<String>,
998        mut reporter: impl ConfigReporter,
999    ) -> Result<String> {
1000        if let Some(value) = value {
1001            self.config_map
1002                .write()
1003                .set(key, value, &mut reporter)
1004                .map_err(Into::into)
1005        } else {
1006            self.config_map
1007                .write()
1008                .reset(key, &mut reporter)
1009                .map_err(Into::into)
1010        }
1011    }
1012
1013    pub fn session_id(&self) -> SessionId {
1014        self.id
1015    }
1016
1017    pub fn running_sql(&self) -> Option<Arc<str>> {
1018        self.exec_context
1019            .lock()
1020            .as_ref()
1021            .and_then(|weak| weak.upgrade())
1022            .map(|context| context.running_sql.clone())
1023    }
1024
1025    pub fn get_cursor_manager(&self) -> Arc<CursorManager> {
1026        self.cursor_manager.clone()
1027    }
1028
1029    pub fn peer_addr(&self) -> &Address {
1030        &self.peer_addr
1031    }
1032
1033    pub fn elapse_since_running_sql(&self) -> Option<u128> {
1034        self.exec_context
1035            .lock()
1036            .as_ref()
1037            .and_then(|weak| weak.upgrade())
1038            .map(|context| context.last_instant.elapsed().as_millis())
1039    }
1040
1041    pub fn elapse_since_last_idle_instant(&self) -> Option<u128> {
1042        self.last_idle_instant
1043            .lock()
1044            .as_ref()
1045            .map(|x| x.elapsed().as_millis())
1046    }
1047
1048    pub fn check_relation_name_duplicated(
1049        &self,
1050        name: ObjectName,
1051        stmt_type: StatementType,
1052        if_not_exists: bool,
1053    ) -> std::result::Result<Either<(), RwPgResponse>, CheckRelationError> {
1054        let db_name = &self.database();
1055        let catalog_reader = self.env().catalog_reader().read_guard();
1056        let (schema_name, relation_name) = {
1057            let (schema_name, relation_name) =
1058                Binder::resolve_schema_qualified_name(db_name, &name)?;
1059            let search_path = self.config().search_path();
1060            let user_name = &self.user_name();
1061            let schema_name = match schema_name {
1062                Some(schema_name) => schema_name,
1063                None => catalog_reader
1064                    .first_valid_schema(db_name, &search_path, user_name)?
1065                    .name(),
1066            };
1067            (schema_name, relation_name)
1068        };
1069        match catalog_reader.check_relation_name_duplicated(db_name, &schema_name, &relation_name) {
1070            Err(e) if if_not_exists => {
1071                if let CatalogErrorInner::Duplicated {
1072                    name,
1073                    under_creation,
1074                    ..
1075                } = e.inner()
1076                {
1077                    // If relation is created, return directly.
1078                    // Otherwise, the job status is `is_creating`. Since frontend receives the catalog asynchronously, we can't
1079                    // determine the real status of the meta at this time. We regard it as `not_exists` and delay the check to meta.
1080                    // Only the type in StreamingJob (defined in streaming_job.rs) and Subscription may be `is_creating`.
1081                    if !*under_creation {
1082                        Ok(Either::Right(
1083                            PgResponse::builder(stmt_type)
1084                                .notice(format!("relation \"{}\" already exists, skipping", name))
1085                                .into(),
1086                        ))
1087                    } else if stmt_type == StatementType::CREATE_SUBSCRIPTION {
1088                        // For now, when a Subscription is creating, we return directly with an additional message.
1089                        // TODO: Subscription should also be processed in the same way as StreamingJob.
1090                        Ok(Either::Right(
1091                            PgResponse::builder(stmt_type)
1092                                .notice(format!(
1093                                    "relation \"{}\" already exists but still creating, skipping",
1094                                    name
1095                                ))
1096                                .into(),
1097                        ))
1098                    } else {
1099                        Ok(Either::Left(()))
1100                    }
1101                } else {
1102                    Err(e.into())
1103                }
1104            }
1105            Err(e) => Err(e.into()),
1106            Ok(_) => Ok(Either::Left(())),
1107        }
1108    }
1109
1110    pub fn check_secret_name_duplicated(&self, name: ObjectName) -> Result<()> {
1111        let db_name = &self.database();
1112        let catalog_reader = self.env().catalog_reader().read_guard();
1113        let (schema_name, secret_name) = {
1114            let (schema_name, secret_name) = Binder::resolve_schema_qualified_name(db_name, &name)?;
1115            let search_path = self.config().search_path();
1116            let user_name = &self.user_name();
1117            let schema_name = match schema_name {
1118                Some(schema_name) => schema_name,
1119                None => catalog_reader
1120                    .first_valid_schema(db_name, &search_path, user_name)?
1121                    .name(),
1122            };
1123            (schema_name, secret_name)
1124        };
1125        catalog_reader
1126            .check_secret_name_duplicated(db_name, &schema_name, &secret_name)
1127            .map_err(RwError::from)
1128    }
1129
1130    pub fn check_connection_name_duplicated(&self, name: ObjectName) -> Result<()> {
1131        let db_name = &self.database();
1132        let catalog_reader = self.env().catalog_reader().read_guard();
1133        let (schema_name, connection_name) = {
1134            let (schema_name, connection_name) =
1135                Binder::resolve_schema_qualified_name(db_name, &name)?;
1136            let search_path = self.config().search_path();
1137            let user_name = &self.user_name();
1138            let schema_name = match schema_name {
1139                Some(schema_name) => schema_name,
1140                None => catalog_reader
1141                    .first_valid_schema(db_name, &search_path, user_name)?
1142                    .name(),
1143            };
1144            (schema_name, connection_name)
1145        };
1146        catalog_reader
1147            .check_connection_name_duplicated(db_name, &schema_name, &connection_name)
1148            .map_err(RwError::from)
1149    }
1150
1151    pub fn check_function_name_duplicated(
1152        &self,
1153        stmt_type: StatementType,
1154        name: ObjectName,
1155        arg_types: &[DataType],
1156        if_not_exists: bool,
1157    ) -> Result<Either<(), RwPgResponse>> {
1158        let db_name = &self.database();
1159        let (schema_name, function_name) = Binder::resolve_schema_qualified_name(db_name, &name)?;
1160        let (database_id, schema_id) = self.get_database_and_schema_id_for_create(schema_name)?;
1161
1162        let catalog_reader = self.env().catalog_reader().read_guard();
1163        if catalog_reader
1164            .get_schema_by_id(database_id, schema_id)?
1165            .get_function_by_name_args(&function_name, arg_types)
1166            .is_some()
1167        {
1168            let full_name = format!(
1169                "{function_name}({})",
1170                arg_types.iter().map(|t| t.to_string()).join(",")
1171            );
1172            if if_not_exists {
1173                Ok(Either::Right(
1174                    PgResponse::builder(stmt_type)
1175                        .notice(format!(
1176                            "function \"{}\" already exists, skipping",
1177                            full_name
1178                        ))
1179                        .into(),
1180                ))
1181            } else {
1182                Err(CatalogError::duplicated("function", full_name).into())
1183            }
1184        } else {
1185            Ok(Either::Left(()))
1186        }
1187    }
1188
1189    /// Also check if the user has the privilege to create in the schema.
1190    pub fn get_database_and_schema_id_for_create(
1191        &self,
1192        schema_name: Option<String>,
1193    ) -> Result<(DatabaseId, SchemaId)> {
1194        let db_name = &self.database();
1195
1196        let search_path = self.config().search_path();
1197        let user_name = &self.user_name();
1198
1199        let catalog_reader = self.env().catalog_reader().read_guard();
1200        let schema = match schema_name {
1201            Some(schema_name) => catalog_reader.get_schema_by_name(db_name, &schema_name)?,
1202            None => catalog_reader.first_valid_schema(db_name, &search_path, user_name)?,
1203        };
1204        let schema_name = schema.name();
1205
1206        check_schema_writable(&schema_name)?;
1207        self.check_privileges(&[ObjectCheckItem::new(
1208            schema.owner(),
1209            AclMode::Create,
1210            schema_name,
1211            schema.id(),
1212        )])?;
1213
1214        let db_id = catalog_reader.get_database_by_name(db_name)?.id();
1215        Ok((db_id, schema.id()))
1216    }
1217
1218    pub fn get_connection_by_name(
1219        &self,
1220        schema_name: Option<String>,
1221        connection_name: &str,
1222    ) -> Result<Arc<ConnectionCatalog>> {
1223        let db_name = &self.database();
1224        let search_path = self.config().search_path();
1225        let user_name = &self.user_name();
1226
1227        let catalog_reader = self.env().catalog_reader().read_guard();
1228        let schema_path = SchemaPath::new(schema_name.as_deref(), &search_path, user_name);
1229        let (connection, _) =
1230            catalog_reader.get_connection_by_name(db_name, schema_path, connection_name)?;
1231
1232        self.check_privileges(&[ObjectCheckItem::new(
1233            connection.owner(),
1234            AclMode::Usage,
1235            connection.name.clone(),
1236            connection.id,
1237        )])?;
1238
1239        Ok(connection.clone())
1240    }
1241
1242    pub fn get_subscription_by_schema_id_name(
1243        &self,
1244        schema_id: SchemaId,
1245        subscription_name: &str,
1246    ) -> Result<Arc<SubscriptionCatalog>> {
1247        let db_name = &self.database();
1248
1249        let catalog_reader = self.env().catalog_reader().read_guard();
1250        let db_id = catalog_reader.get_database_by_name(db_name)?.id();
1251        let schema = catalog_reader.get_schema_by_id(db_id, schema_id)?;
1252        let subscription = schema
1253            .get_subscription_by_name(subscription_name)
1254            .ok_or_else(|| {
1255                RwError::from(ErrorCode::ItemNotFound(format!(
1256                    "subscription {} not found",
1257                    subscription_name
1258                )))
1259            })?;
1260        Ok(subscription.clone())
1261    }
1262
1263    pub fn get_subscription_by_name(
1264        &self,
1265        schema_name: Option<String>,
1266        subscription_name: &str,
1267    ) -> Result<Arc<SubscriptionCatalog>> {
1268        let db_name = &self.database();
1269        let search_path = self.config().search_path();
1270        let user_name = &self.user_name();
1271
1272        let catalog_reader = self.env().catalog_reader().read_guard();
1273        let schema_path = SchemaPath::new(schema_name.as_deref(), &search_path, user_name);
1274        let (subscription, _) =
1275            catalog_reader.get_subscription_by_name(db_name, schema_path, subscription_name)?;
1276        Ok(subscription.clone())
1277    }
1278
1279    pub fn get_table_by_id(&self, table_id: TableId) -> Result<Arc<TableCatalog>> {
1280        let catalog_reader = self.env().catalog_reader().read_guard();
1281        Ok(catalog_reader.get_any_table_by_id(table_id)?.clone())
1282    }
1283
1284    pub fn get_table_by_name(
1285        &self,
1286        table_name: &str,
1287        db_id: DatabaseId,
1288        schema_id: SchemaId,
1289    ) -> Result<Arc<TableCatalog>> {
1290        let catalog_reader = self.env().catalog_reader().read_guard();
1291        let table = catalog_reader
1292            .get_schema_by_id(db_id, schema_id)?
1293            .get_created_table_by_name(table_name)
1294            .ok_or_else(|| {
1295                Error::new(
1296                    ErrorKind::InvalidInput,
1297                    format!("table \"{}\" does not exist", table_name),
1298                )
1299            })?;
1300
1301        self.check_privileges(&[ObjectCheckItem::new(
1302            table.owner(),
1303            AclMode::Select,
1304            table_name.to_owned(),
1305            table.id,
1306        )])?;
1307
1308        Ok(table.clone())
1309    }
1310
1311    pub fn get_secret_by_name(
1312        &self,
1313        schema_name: Option<String>,
1314        secret_name: &str,
1315    ) -> Result<Arc<SecretCatalog>> {
1316        let db_name = &self.database();
1317        let search_path = self.config().search_path();
1318        let user_name = &self.user_name();
1319
1320        let catalog_reader = self.env().catalog_reader().read_guard();
1321        let schema_path = SchemaPath::new(schema_name.as_deref(), &search_path, user_name);
1322        let (secret, _) = catalog_reader.get_secret_by_name(db_name, schema_path, secret_name)?;
1323
1324        self.check_privileges(&[ObjectCheckItem::new(
1325            secret.owner(),
1326            AclMode::Usage,
1327            secret.name.clone(),
1328            secret.id,
1329        )])?;
1330
1331        Ok(secret.clone())
1332    }
1333
1334    /// Returns `None` when the table's committed epoch has not reached `min_epoch`.
1335    pub async fn list_change_log_epochs(
1336        &self,
1337        table_id: TableId,
1338        min_epoch: u64,
1339        max_count: u32,
1340    ) -> Result<Option<Vec<u64>>> {
1341        let committed_epoch = self
1342            .env
1343            .hummock_snapshot_manager()
1344            .acquire()
1345            .version()
1346            .state_table_info
1347            .info()
1348            .get(&table_id)
1349            .map(|s| s.committed_epoch)
1350            .ok_or_else(|| anyhow!("table id {table_id} has been dropped"))?;
1351        if min_epoch > committed_epoch {
1352            return Ok(None);
1353        }
1354        let ret = self
1355            .env
1356            .meta_client_ref()
1357            .get_hummock_table_change_log(
1358                Some(min_epoch),
1359                Some(committed_epoch),
1360                Some(iter::once(table_id).collect()),
1361                true,
1362                Some(max_count),
1363            )
1364            .await?;
1365        let Some(e) = ret.get(&table_id) else {
1366            return Ok(Some(vec![]));
1367        };
1368        Ok(Some(
1369            e.iter()
1370                .flat_map(|l| l.epochs())
1371                .filter(|e| *e >= min_epoch && *e <= committed_epoch)
1372                .take(max_count as usize)
1373                .collect(),
1374        ))
1375    }
1376
1377    pub fn clear_cancel_query_flag(&self) {
1378        let mut flag = self.current_query_cancel_flag.lock();
1379        *flag = None;
1380    }
1381
1382    pub fn reset_cancel_query_flag(&self) -> ShutdownToken {
1383        let mut flag = self.current_query_cancel_flag.lock();
1384        let (shutdown_tx, shutdown_rx) = ShutdownToken::new();
1385        *flag = Some(shutdown_tx);
1386        shutdown_rx
1387    }
1388
1389    pub fn set_cancel_query_flag(&self, shutdown_tx: ShutdownSender) {
1390        let mut flag = self.current_query_cancel_flag.lock();
1391        *flag = Some(shutdown_tx);
1392    }
1393
1394    pub fn cancel_current_query(&self) {
1395        let mut flag_guard = self.current_query_cancel_flag.lock();
1396        if let Some(sender) = flag_guard.take() {
1397            info!("Trying to cancel query in local mode.");
1398            // Current running query is in local mode
1399            sender.cancel();
1400            info!("Cancel query request sent.");
1401        }
1402        info!("Trying to cancel query in distributed mode.");
1403        self.env.query_manager().cancel_queries_in_session(self.id)
1404    }
1405
1406    pub fn cancel_current_creating_job(&self) {
1407        self.env.creating_streaming_job_tracker.abort_jobs(self.id);
1408    }
1409
1410    /// This function only used for test now.
1411    /// Maybe we can remove it in the future.
1412    pub async fn run_statement(
1413        self: Arc<Self>,
1414        sql: Arc<str>,
1415        formats: Vec<Format>,
1416    ) -> std::result::Result<PgResponse<PgResponseStream>, BoxedError> {
1417        // Parse sql.
1418        let mut stmts = Parser::parse_sql(&sql)?;
1419        if stmts.is_empty() {
1420            return Ok(PgResponse::empty_result(
1421                pgwire::pg_response::StatementType::EMPTY,
1422            ));
1423        }
1424        if stmts.len() > 1 {
1425            return Ok(
1426                PgResponse::builder(pgwire::pg_response::StatementType::EMPTY)
1427                    .notice("cannot insert multiple commands into statement")
1428                    .into(),
1429            );
1430        }
1431        let stmt = stmts.swap_remove(0);
1432        let rsp = Box::pin(handle(self, stmt, sql.clone(), formats)).await?;
1433        Ok(rsp)
1434    }
1435
1436    pub fn notice_to_user(&self, str: impl Into<String>) {
1437        let notice = str.into();
1438        tracing::trace!(notice, "notice to user");
1439        self.notice_tx
1440            .send(notice)
1441            .expect("notice channel should not be closed");
1442    }
1443
1444    pub fn is_barrier_read(&self) -> bool {
1445        match self.config().visibility_mode() {
1446            VisibilityMode::Default => self.env.batch_config.enable_barrier_read,
1447            VisibilityMode::All => true,
1448            VisibilityMode::Checkpoint => false,
1449        }
1450    }
1451
1452    pub fn statement_timeout(&self) -> Duration {
1453        if self.config().statement_timeout().millis() == 0 {
1454            Duration::from_secs(self.env.batch_config.statement_timeout_in_sec as u64)
1455        } else {
1456            Duration::from_millis(self.config().statement_timeout().millis() as u64)
1457        }
1458    }
1459
1460    pub fn create_temporary_source(&self, source: SourceCatalog) {
1461        self.temporary_source_manager
1462            .lock()
1463            .create_source(source.name.clone(), source);
1464    }
1465
1466    pub fn get_temporary_source(&self, name: &str) -> Option<SourceCatalog> {
1467        self.temporary_source_manager
1468            .lock()
1469            .get_source(name)
1470            .cloned()
1471    }
1472
1473    pub fn drop_temporary_source(&self, name: &str) {
1474        self.temporary_source_manager.lock().drop_source(name);
1475    }
1476
1477    pub fn temporary_source_manager(&self) -> TemporarySourceManager {
1478        self.temporary_source_manager.lock().clone()
1479    }
1480
1481    pub fn create_staging_table(&self, table: TableCatalog) {
1482        self.staging_catalog_manager
1483            .lock()
1484            .create_table(table.name.clone(), table);
1485    }
1486
1487    pub fn drop_staging_table(&self, name: &str) {
1488        self.staging_catalog_manager.lock().drop_table(name);
1489    }
1490
1491    pub fn staging_catalog_manager(&self) -> StagingCatalogManager {
1492        self.staging_catalog_manager.lock().clone()
1493    }
1494
1495    pub async fn check_cluster_limits(&self) -> Result<()> {
1496        if self.config().bypass_cluster_limits() {
1497            return Ok(());
1498        }
1499
1500        let gen_message = |ActorCountPerParallelism {
1501                               worker_id_to_actor_count,
1502                               hard_limit,
1503                               soft_limit,
1504                           }: ActorCountPerParallelism,
1505                           exceed_hard_limit: bool|
1506         -> String {
1507            let (limit_type, action) = if exceed_hard_limit {
1508                ("critical", "Scale the cluster immediately to proceed.")
1509            } else {
1510                (
1511                    "recommended",
1512                    "Consider scaling the cluster for optimal performance.",
1513                )
1514            };
1515            format!(
1516                r#"Actor count per parallelism exceeds the {limit_type} limit.
1517
1518Depending on your workload, this may overload the cluster and cause performance/stability issues. {action}
1519
1520HINT:
1521- For best practices on managing streaming jobs: https://docs.risingwave.com/operate/manage-a-large-number-of-streaming-jobs
1522- To bypass the check (if the cluster load is acceptable): `[ALTER SYSTEM] SET bypass_cluster_limits TO true`.
1523  See https://docs.risingwave.com/operate/view-configure-runtime-parameters#how-to-configure-runtime-parameters
1524- Contact us via slack or https://risingwave.com/contact-us/ for further enquiry.
1525
1526DETAILS:
1527- hard limit: {hard_limit}
1528- soft limit: {soft_limit}
1529- worker_id_to_actor_count: {worker_id_to_actor_count:?}"#,
1530            )
1531        };
1532
1533        let limits = self.env().meta_client().get_cluster_limits().await?;
1534        for limit in limits {
1535            match limit {
1536                cluster_limit::ClusterLimit::ActorCount(l) => {
1537                    if l.exceed_hard_limit() {
1538                        return Err(RwError::from(ErrorCode::ProtocolError(gen_message(
1539                            l, true,
1540                        ))));
1541                    } else if l.exceed_soft_limit() {
1542                        self.notice_to_user(gen_message(l, false));
1543                    }
1544                }
1545            }
1546        }
1547        Ok(())
1548    }
1549}
1550
1551pub static SESSION_MANAGER: std::sync::OnceLock<Arc<SessionManagerImpl>> =
1552    std::sync::OnceLock::new();
1553
1554pub struct SessionManagerImpl {
1555    env: FrontendEnv,
1556    _join_handles: Vec<JoinHandle<()>>,
1557    _shutdown_senders: Vec<Sender<()>>,
1558    number: AtomicI32,
1559}
1560
1561impl SessionManager for SessionManagerImpl {
1562    type Error = RwError;
1563    type Session = SessionImpl;
1564
1565    fn create_dummy_session(&self, database_id: DatabaseId) -> Result<Arc<Self::Session>> {
1566        let dummy_addr = Address::Tcp(SocketAddr::new(
1567            IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
1568            5691, // port of meta
1569        ));
1570
1571        // Always use the built-in super user for dummy sessions.
1572        // This avoids permission checks tied to a specific user_id.
1573        self.connect_inner(
1574            database_id,
1575            risingwave_common::catalog::DEFAULT_SUPER_USER,
1576            Arc::new(dummy_addr),
1577        )
1578    }
1579
1580    fn connect(
1581        &self,
1582        database: &str,
1583        user_name: &str,
1584        peer_addr: AddressRef,
1585    ) -> Result<Arc<Self::Session>> {
1586        let catalog_reader = self.env.catalog_reader();
1587        let reader = catalog_reader.read_guard();
1588        let database_id = reader.get_database_by_name(database)?.id();
1589
1590        self.connect_inner(database_id, user_name, peer_addr)
1591    }
1592
1593    /// Used when cancel request happened.
1594    fn cancel_queries_in_session(&self, session_id: SessionId) {
1595        self.env.cancel_queries_in_session(session_id);
1596    }
1597
1598    fn cancel_creating_jobs_in_session(&self, session_id: SessionId) {
1599        self.env.cancel_creating_jobs_in_session(session_id);
1600    }
1601
1602    fn end_session(&self, session: &Self::Session) {
1603        self.delete_session(&session.session_id());
1604    }
1605
1606    async fn shutdown(&self) {
1607        // Clean up the session map.
1608        self.env.sessions_map().write().clear();
1609        // Unregister from the meta service.
1610        self.env.meta_client().try_unregister().await;
1611    }
1612}
1613
1614impl SessionManagerImpl {
1615    pub async fn new(opts: FrontendOpts) -> Result<Self> {
1616        // TODO(shutdown): only save join handles that **need** to be shutdown
1617        let (env, join_handles, shutdown_senders) = FrontendEnv::init(opts).await?;
1618        Ok(Self {
1619            env,
1620            _join_handles: join_handles,
1621            _shutdown_senders: shutdown_senders,
1622            number: AtomicI32::new(0),
1623        })
1624    }
1625
1626    pub(crate) fn env(&self) -> &FrontendEnv {
1627        &self.env
1628    }
1629
1630    fn insert_session(&self, session: Arc<SessionImpl>) {
1631        let active_sessions = {
1632            let mut write_guard = self.env.sessions_map.write();
1633            write_guard.insert(session.id(), session);
1634            write_guard.len()
1635        };
1636        self.env
1637            .frontend_metrics
1638            .active_sessions
1639            .set(active_sessions as i64);
1640    }
1641
1642    fn delete_session(&self, session_id: &SessionId) {
1643        let active_sessions = {
1644            let mut write_guard = self.env.sessions_map.write();
1645            write_guard.remove(session_id);
1646            write_guard.len()
1647        };
1648        self.env
1649            .frontend_metrics
1650            .active_sessions
1651            .set(active_sessions as i64);
1652    }
1653
1654    fn connect_inner(
1655        &self,
1656        database_id: DatabaseId,
1657        user_name: &str,
1658        peer_addr: AddressRef,
1659    ) -> Result<Arc<SessionImpl>> {
1660        let catalog_reader = self.env.catalog_reader();
1661        let reader = catalog_reader.read_guard();
1662        let (database_name, database_owner) = {
1663            let db = reader.get_database_by_id(database_id)?;
1664            (db.name(), db.owner())
1665        };
1666
1667        let user_reader = self.env.user_info_reader();
1668        let reader = user_reader.read_guard();
1669        if let Some(user) = reader.get_user_by_name(user_name) {
1670            if !user.can_login {
1671                bail_permission_denied!("User {} is not allowed to login", user_name);
1672            }
1673            let has_privilege = user.has_privilege(database_id, AclMode::Connect);
1674            if !user.is_super && database_owner != user.id && !has_privilege {
1675                bail_permission_denied!("User does not have CONNECT privilege.");
1676            }
1677
1678            // Check HBA configuration for LDAP authentication
1679            let (connection_type, client_addr) = match peer_addr.as_ref() {
1680                Address::Tcp(socket_addr) => (ConnectionType::Host, Some(&socket_addr.ip())),
1681                Address::Unix(_) => (ConnectionType::Local, None),
1682            };
1683            tracing::debug!(
1684                "receive connection: type={:?}, client_addr={:?}",
1685                connection_type,
1686                client_addr
1687            );
1688
1689            let hba_entry_opt = self.env.frontend_config().hba_config.find_matching_entry(
1690                &connection_type,
1691                database_name,
1692                user_name,
1693                client_addr,
1694            );
1695
1696            let Some(hba_entry_opt) = hba_entry_opt else {
1697                bail_permission_denied!(
1698                    "no pg_hba.conf entry for host \"{peer_addr}\", user \"{user_name}\", database \"{database_name}\""
1699                );
1700            };
1701
1702            // Determine the user authenticator based on the user's auth info.
1703            let authenticator_by_info = || -> Result<UserAuthenticator> {
1704                let authenticator = match &user.auth_info {
1705                    None => UserAuthenticator::None,
1706                    Some(auth_info) => match auth_info.encryption_type() {
1707                        EncryptionType::Plaintext => {
1708                            UserAuthenticator::ClearText(auth_info.encrypted_value.clone())
1709                        }
1710                        EncryptionType::Md5 => {
1711                            let mut salt = [0; 4];
1712                            let mut rng = rand::rng();
1713                            rng.fill_bytes(&mut salt);
1714                            UserAuthenticator::Md5WithSalt {
1715                                encrypted_password: md5_hash_with_salt(
1716                                    &auth_info.encrypted_value,
1717                                    &salt,
1718                                ),
1719                                salt,
1720                            }
1721                        }
1722                        EncryptionType::Oauth => UserAuthenticator::OAuth {
1723                            metadata: auth_info.metadata.clone(),
1724                            cluster_id: self.env.meta_client().cluster_id().to_owned(),
1725                        },
1726                        _ => {
1727                            bail_protocol_error!(
1728                                "Unsupported auth type: {}",
1729                                auth_info.encryption_type().as_str_name()
1730                            );
1731                        }
1732                    },
1733                };
1734                Ok(authenticator)
1735            };
1736
1737            let user_authenticator = match (&hba_entry_opt.auth_method, &user.auth_info) {
1738                (AuthMethod::Trust, _) => UserAuthenticator::None,
1739                // For backward compatibility, we allow password auth method to work with any auth info.
1740                (AuthMethod::Password, _) => authenticator_by_info()?,
1741                (AuthMethod::Md5, Some(auth_info))
1742                    if auth_info.encryption_type() == EncryptionType::Md5 =>
1743                {
1744                    authenticator_by_info()?
1745                }
1746                (AuthMethod::OAuth, Some(auth_info))
1747                    if auth_info.encryption_type() == EncryptionType::Oauth =>
1748                {
1749                    authenticator_by_info()?
1750                }
1751                (AuthMethod::Ldap, _) => {
1752                    UserAuthenticator::Ldap(user_name.to_owned(), hba_entry_opt.clone())
1753                }
1754                _ => {
1755                    bail_permission_denied!(
1756                        "password authentication failed for user \"{user_name}\""
1757                    );
1758                }
1759            };
1760
1761            // Assign a session id and insert into sessions map (for cancel request).
1762            let secret_key = self.number.fetch_add(1, Ordering::Relaxed);
1763            // Use a trivial strategy: process_id and secret_key are equal.
1764            let id = (secret_key, secret_key);
1765            // Read session params snapshot from frontend env.
1766            let session_config = self.env.session_params_snapshot();
1767
1768            let session_impl: Arc<SessionImpl> = SessionImpl::new(
1769                self.env.clone(),
1770                AuthContext::new(database_name.to_owned(), user_name.to_owned(), user.id),
1771                user_authenticator,
1772                id,
1773                peer_addr,
1774                session_config,
1775            )
1776            .into();
1777            self.insert_session(session_impl.clone());
1778
1779            Ok(session_impl)
1780        } else {
1781            bail_catalog_error!("Role {} does not exist", user_name);
1782        }
1783    }
1784}
1785
1786impl Session for SessionImpl {
1787    type Error = RwError;
1788    type Portal = Portal;
1789    type PreparedStatement = PrepareStatement;
1790    type ValuesStream = PgResponseStream;
1791
1792    /// A copy of `run_statement` but exclude the parser part so each run must be at most one
1793    /// statement. The str sql use the `to_string` of AST. Consider Reuse later.
1794    async fn run_one_query(
1795        self: Arc<Self>,
1796        stmt: Statement,
1797        format: Format,
1798    ) -> Result<PgResponse<PgResponseStream>> {
1799        let string = stmt.to_string();
1800        let sql_str = string.as_str();
1801        let sql: Arc<str> = Arc::from(sql_str);
1802        // The handle can be slow. Release potential large String early.
1803        drop(string);
1804        let rsp = Box::pin(handle(self, stmt, sql, vec![format])).await?;
1805        Ok(rsp)
1806    }
1807
1808    fn user_authenticator(&self) -> &UserAuthenticator {
1809        &self.user_authenticator
1810    }
1811
1812    fn id(&self) -> SessionId {
1813        self.id
1814    }
1815
1816    async fn parse(
1817        self: Arc<Self>,
1818        statement: Option<Statement>,
1819        params_types: Vec<Option<DataType>>,
1820    ) -> Result<PrepareStatement> {
1821        Ok(if let Some(statement) = statement {
1822            handle_parse(self, statement, params_types).await?
1823        } else {
1824            PrepareStatement::Empty
1825        })
1826    }
1827
1828    fn bind(
1829        self: Arc<Self>,
1830        prepare_statement: PrepareStatement,
1831        params: Vec<Option<Bytes>>,
1832        param_formats: Vec<Format>,
1833        result_formats: Vec<Format>,
1834    ) -> Result<Portal> {
1835        handle_bind(prepare_statement, params, param_formats, result_formats)
1836    }
1837
1838    async fn execute(self: Arc<Self>, portal: Portal) -> Result<PgResponse<PgResponseStream>> {
1839        let rsp = Box::pin(handle_execute(self, portal)).await?;
1840        Ok(rsp)
1841    }
1842
1843    fn describe_statement(
1844        self: Arc<Self>,
1845        prepare_statement: PrepareStatement,
1846    ) -> Result<(Vec<DataType>, Vec<PgFieldDescriptor>)> {
1847        Ok(match prepare_statement {
1848            PrepareStatement::Empty => (vec![], vec![]),
1849            PrepareStatement::Prepared(prepare_statement) => (
1850                prepare_statement.bound_result.param_types,
1851                infer(
1852                    Some(prepare_statement.bound_result.bound),
1853                    prepare_statement.statement,
1854                )?,
1855            ),
1856            PrepareStatement::PureStatement(statement) => (vec![], infer(None, statement)?),
1857        })
1858    }
1859
1860    fn describe_portal(self: Arc<Self>, portal: Portal) -> Result<Vec<PgFieldDescriptor>> {
1861        match portal {
1862            Portal::Empty => Ok(vec![]),
1863            Portal::Portal(portal) => {
1864                let mut columns = infer(Some(portal.bound_result.bound), portal.statement)?;
1865                let formats = FormatIterator::new(&portal.result_formats, columns.len())
1866                    .map_err(|e| RwError::from(ErrorCode::ProtocolError(e)))?;
1867                columns.iter_mut().zip_eq_fast(formats).for_each(|(c, f)| {
1868                    if f == Format::Binary {
1869                        c.set_to_binary()
1870                    }
1871                });
1872                Ok(columns)
1873            }
1874            Portal::PureStatement(statement) => Ok(infer(None, statement)?),
1875        }
1876    }
1877
1878    fn get_config(&self, key: &str) -> Result<String> {
1879        self.config().get(key).map_err(Into::into)
1880    }
1881
1882    fn set_config(&self, key: &str, value: String) -> Result<String> {
1883        Self::set_config(self, key, value)
1884    }
1885
1886    async fn next_notice(self: &Arc<Self>) -> String {
1887        std::future::poll_fn(|cx| self.clone().notice_rx.lock().poll_recv(cx))
1888            .await
1889            .expect("notice channel should not be closed")
1890    }
1891
1892    fn transaction_status(&self) -> TransactionStatus {
1893        match &*self.txn.lock() {
1894            transaction::State::Initial | transaction::State::Implicit(_) => {
1895                TransactionStatus::Idle
1896            }
1897            transaction::State::Explicit(_) => TransactionStatus::InTransaction,
1898            // TODO: failed transaction
1899        }
1900    }
1901
1902    /// Init and return an `ExecContextGuard` which could be used as a guard to represent the execution flow.
1903    fn init_exec_context(&self, sql: Arc<str>) -> ExecContextGuard {
1904        let exec_context = Arc::new(ExecContext {
1905            running_sql: sql,
1906            last_instant: Instant::now(),
1907            last_idle_instant: self.last_idle_instant.clone(),
1908        });
1909        *self.exec_context.lock() = Some(Arc::downgrade(&exec_context));
1910        // unset idle state, since there is a sql running
1911        *self.last_idle_instant.lock() = None;
1912        ExecContextGuard::new(exec_context)
1913    }
1914
1915    /// Check whether idle transaction timeout.
1916    /// If yes, unpin snapshot and return an `IdleInTxnTimeout` error.
1917    fn check_idle_in_transaction_timeout(&self) -> PsqlResult<()> {
1918        // In transaction.
1919        if matches!(self.transaction_status(), TransactionStatus::InTransaction) {
1920            let idle_in_transaction_session_timeout =
1921                self.config().idle_in_transaction_session_timeout() as u128;
1922            // Idle transaction timeout has been enabled.
1923            if idle_in_transaction_session_timeout != 0 {
1924                // Hold the `exec_context` lock to ensure no new sql coming when unpin_snapshot.
1925                let guard = self.exec_context.lock();
1926                // No running sql i.e. idle
1927                if guard.as_ref().and_then(|weak| weak.upgrade()).is_none() {
1928                    // Idle timeout.
1929                    if let Some(elapse_since_last_idle_instant) =
1930                        self.elapse_since_last_idle_instant()
1931                        && elapse_since_last_idle_instant > idle_in_transaction_session_timeout
1932                    {
1933                        return Err(PsqlError::IdleInTxnTimeout);
1934                    }
1935                }
1936            }
1937        }
1938        Ok(())
1939    }
1940
1941    fn user(&self) -> String {
1942        self.user_name()
1943    }
1944}
1945
1946/// Returns row description of the statement
1947fn infer(bound: Option<BoundStatement>, stmt: Statement) -> Result<Vec<PgFieldDescriptor>> {
1948    match stmt {
1949        Statement::Query(_)
1950        | Statement::Insert { .. }
1951        | Statement::Delete { .. }
1952        | Statement::Update { .. }
1953        | Statement::FetchCursor { .. } => Ok(bound
1954            .unwrap()
1955            .output_fields()
1956            .iter()
1957            .map(to_pg_field)
1958            .collect()),
1959        Statement::ShowObjects {
1960            object: show_object,
1961            ..
1962        } => Ok(infer_show_object(&show_object)),
1963        Statement::ShowCreateObject { .. } => Ok(infer_show_create_object()),
1964        Statement::ShowTransactionIsolationLevel => {
1965            let name = "transaction_isolation";
1966            Ok(infer_show_variable(name))
1967        }
1968        Statement::ShowVariable { variable } => {
1969            let name = &variable[0].real_value().to_lowercase();
1970            Ok(infer_show_variable(name))
1971        }
1972        Statement::Describe { name: _, kind } => Ok(infer_describe(&kind)),
1973        Statement::Explain { .. } => Ok(vec![PgFieldDescriptor::new(
1974            "QUERY PLAN".to_owned(),
1975            DataType::Varchar.to_oid(),
1976            DataType::Varchar.type_len(),
1977        )]),
1978        _ => Ok(vec![]),
1979    }
1980}
1981
1982pub struct WorkerProcessId {
1983    pub worker_id: WorkerId,
1984    pub process_id: i32,
1985}
1986
1987impl WorkerProcessId {
1988    pub fn new(worker_id: WorkerId, process_id: i32) -> Self {
1989        Self {
1990            worker_id,
1991            process_id,
1992        }
1993    }
1994}
1995
1996impl Display for WorkerProcessId {
1997    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1998        write!(f, "{}:{}", self.worker_id, self.process_id)
1999    }
2000}
2001
2002impl TryFrom<String> for WorkerProcessId {
2003    type Error = String;
2004
2005    fn try_from(worker_process_id: String) -> std::result::Result<Self, Self::Error> {
2006        const INVALID: &str = "invalid WorkerProcessId";
2007        let splits: Vec<&str> = worker_process_id.split(":").collect();
2008        if splits.len() != 2 {
2009            return Err(INVALID.to_owned());
2010        }
2011        let Ok(worker_id) = splits[0].parse::<u32>() else {
2012            return Err(INVALID.to_owned());
2013        };
2014        let Ok(process_id) = splits[1].parse::<i32>() else {
2015            return Err(INVALID.to_owned());
2016        };
2017        Ok(WorkerProcessId::new(worker_id.into(), process_id))
2018    }
2019}
2020
2021pub fn cancel_queries_in_session(session_id: SessionId, sessions_map: SessionMapRef) -> bool {
2022    let guard = sessions_map.read();
2023    if let Some(session) = guard.get(&session_id) {
2024        session.cancel_current_query();
2025        true
2026    } else {
2027        info!("Current session finished, ignoring cancel query request");
2028        false
2029    }
2030}
2031
2032pub fn cancel_creating_jobs_in_session(session_id: SessionId, sessions_map: SessionMapRef) -> bool {
2033    let guard = sessions_map.read();
2034    if let Some(session) = guard.get(&session_id) {
2035        session.cancel_current_creating_job();
2036        true
2037    } else {
2038        info!("Current session finished, ignoring cancel creating request");
2039        false
2040    }
2041}