Skip to main content

session/
lib.rs

1// Copyright 2023 Greptime Team
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
15pub mod context;
16pub mod hints;
17pub mod protocol_ctx;
18pub mod query_id;
19pub mod query_options;
20pub mod session_config;
21pub mod table_name;
22
23use std::collections::{HashMap, VecDeque};
24use std::net::SocketAddr;
25use std::sync::{Arc, RwLock};
26use std::time::Duration;
27
28use auth::UserInfoRef;
29use common_catalog::build_db_string;
30use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
31use common_recordbatch::cursor::RecordBatchStreamCursor;
32pub use common_session::ReadPreference;
33use common_time::Timezone;
34use common_time::timezone::get_timezone;
35use context::{ConfigurationVariables, QueryContextBuilder};
36use derive_more::Debug;
37
38use crate::context::{Channel, ConnInfo, QueryContextRef, dialect_for_channel};
39
40/// Maximum number of warnings to store per session (similar to MySQL's max_error_count)
41const MAX_WARNINGS: usize = 64;
42
43/// Session for persistent connection such as MySQL, PostgreSQL etc.
44#[derive(Debug)]
45pub struct Session {
46    catalog: RwLock<String>,
47    mutable_inner: Arc<RwLock<MutableInner>>,
48    conn_info: ConnInfo,
49    configuration_variables: Arc<ConfigurationVariables>,
50    // the process id to use when killing the query
51    process_id: u32,
52}
53
54pub type SessionRef = Arc<Session>;
55
56/// A container for mutable items in query context
57#[derive(Debug, Clone)]
58pub(crate) struct MutableInner {
59    schema: String,
60    user_info: UserInfoRef,
61    timezone: Timezone,
62    query_timeout: Option<Duration>,
63    read_preference: ReadPreference,
64    /// Request-level WAL policy for ordinary inserts.
65    skip_wal: bool,
66    #[debug(skip)]
67    pub(crate) cursors: HashMap<String, Arc<RecordBatchStreamCursor>>,
68    /// Warning messages for MySQL SHOW WARNINGS support
69    warnings: VecDeque<String>,
70}
71
72impl Default for MutableInner {
73    fn default() -> Self {
74        Self {
75            schema: DEFAULT_SCHEMA_NAME.into(),
76            user_info: auth::userinfo_by_name(None),
77            timezone: get_timezone(None).clone(),
78            query_timeout: None,
79            read_preference: ReadPreference::Leader,
80            skip_wal: false,
81            cursors: HashMap::with_capacity(0),
82            warnings: VecDeque::new(),
83        }
84    }
85}
86
87impl Session {
88    pub fn new(
89        addr: Option<SocketAddr>,
90        channel: Channel,
91        configuration_variables: ConfigurationVariables,
92        process_id: u32,
93    ) -> Self {
94        Session {
95            catalog: RwLock::new(DEFAULT_CATALOG_NAME.into()),
96            conn_info: ConnInfo::new(addr, channel),
97            configuration_variables: Arc::new(configuration_variables),
98            mutable_inner: Arc::new(RwLock::new(MutableInner::default())),
99            process_id,
100        }
101    }
102
103    pub fn new_query_context(&self) -> QueryContextRef {
104        QueryContextBuilder::default()
105            // catalog is not allowed for update in query context so we use
106            // string here
107            .current_catalog(self.catalog.read().unwrap().clone())
108            .mutable_session_data(self.mutable_inner.clone())
109            .sql_dialect(dialect_for_channel(self.conn_info.channel))
110            .configuration_parameter(self.configuration_variables.clone())
111            .channel(self.conn_info.channel)
112            .process_id(self.process_id)
113            .conn_info(self.conn_info.clone())
114            .build()
115            .into()
116    }
117
118    /// Cursors are shared across query contexts created from this session.
119    pub fn get_cursor(&self, name: &str) -> Option<Arc<RecordBatchStreamCursor>> {
120        let guard = self.mutable_inner.read().unwrap();
121        guard.cursors.get(name).cloned()
122    }
123
124    pub fn conn_info(&self) -> &ConnInfo {
125        &self.conn_info
126    }
127
128    pub fn timezone(&self) -> Timezone {
129        self.mutable_inner.read().unwrap().timezone.clone()
130    }
131
132    pub fn read_preference(&self) -> ReadPreference {
133        self.mutable_inner.read().unwrap().read_preference
134    }
135
136    pub fn set_timezone(&self, tz: Timezone) {
137        let mut inner = self.mutable_inner.write().unwrap();
138        inner.timezone = tz;
139    }
140
141    pub fn set_read_preference(&self, read_preference: ReadPreference) {
142        self.mutable_inner.write().unwrap().read_preference = read_preference;
143    }
144
145    pub fn user_info(&self) -> UserInfoRef {
146        self.mutable_inner.read().unwrap().user_info.clone()
147    }
148
149    pub fn set_user_info(&self, user_info: UserInfoRef) {
150        self.mutable_inner.write().unwrap().user_info = user_info;
151    }
152
153    pub fn set_catalog(&self, catalog: String) {
154        *self.catalog.write().unwrap() = catalog;
155    }
156
157    pub fn catalog(&self) -> String {
158        self.catalog.read().unwrap().clone()
159    }
160
161    pub fn schema(&self) -> String {
162        self.mutable_inner.read().unwrap().schema.clone()
163    }
164
165    pub fn set_schema(&self, schema: String) {
166        self.mutable_inner.write().unwrap().schema = schema;
167    }
168
169    pub fn get_db_string(&self) -> String {
170        build_db_string(&self.catalog(), &self.schema())
171    }
172
173    pub fn process_id(&self) -> u32 {
174        self.process_id
175    }
176
177    pub fn warnings_count(&self) -> usize {
178        self.mutable_inner.read().unwrap().warnings.len()
179    }
180
181    pub fn warnings(&self) -> Vec<String> {
182        self.mutable_inner
183            .read()
184            .unwrap()
185            .warnings
186            .iter()
187            .cloned()
188            .collect()
189    }
190
191    /// Add a warning message. If the limit is reached, discard the oldest warning.
192    pub fn add_warning(&self, warning: String) {
193        let mut inner = self.mutable_inner.write().unwrap();
194        if inner.warnings.len() >= MAX_WARNINGS {
195            inner.warnings.pop_front();
196        }
197        inner.warnings.push_back(warning);
198    }
199
200    pub fn clear_warnings(&self) {
201        let mut inner = self.mutable_inner.write().unwrap();
202        if inner.warnings.is_empty() {
203            return;
204        }
205        inner.warnings.clear();
206    }
207}