Skip to main content

session/
context.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
15use std::collections::HashMap;
16use std::fmt::{Display, Formatter};
17use std::net::SocketAddr;
18use std::str::FromStr;
19use std::sync::{Arc, RwLock};
20use std::time::Duration;
21
22use api::v1::ExplainOptions;
23use api::v1::region::RegionRequestHeader;
24use arc_swap::ArcSwap;
25use auth::UserInfoRef;
26pub use common_base::protocol::Channel;
27use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
28use common_catalog::{build_db_string, parse_catalog_and_schema_from_db_string};
29use common_recordbatch::cursor::RecordBatchStreamCursor;
30use common_telemetry::warn;
31use common_time::Timezone;
32use common_time::timezone::parse_timezone;
33use datafusion_common::config::ConfigOptions;
34use derive_builder::Builder;
35use sql::dialect::{Dialect, GenericDialect, GreptimeDbDialect, MySqlDialect, PostgreSqlDialect};
36
37pub use crate::hints::{
38    LIVE_ANALYZE_METRICS_EXTENSION_KEY, READ_PREFERENCE_EXTENSION_KEY,
39    REMOTE_QUERY_ID_EXTENSION_KEY, SUPPORT_FLIGHT_METRICS_BEFORE_BATCH_EXTENSION_KEY,
40};
41use crate::protocol_ctx::ProtocolCtx;
42use crate::query_id::QueryId;
43use crate::session_config::{
44    InvalidConfigValueSnafu, PGByteaOutputValue, PGDateOrder, PGDateTimeStyle, PGIntervalStyle,
45};
46use crate::{MutableInner, ReadPreference};
47
48pub type QueryContextRef = Arc<QueryContext>;
49pub type ConnInfoRef = Arc<ConnInfo>;
50
51pub const FLIGHT_METRICS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
52
53const CURSOR_COUNT_WARNING_LIMIT: usize = 10;
54
55pub fn generate_remote_query_id() -> String {
56    generate_remote_query_id_value().to_string()
57}
58
59pub fn generate_remote_query_id_value() -> QueryId {
60    QueryId::new()
61}
62
63#[derive(Debug, Builder, Clone)]
64#[builder(pattern = "owned")]
65#[builder(build_fn(skip))]
66pub struct QueryContext {
67    current_catalog: String,
68    /// mapping of RegionId to SequenceNumber, for snapshot read, meaning that the read should only
69    /// container data that was committed before(and include) the given sequence number
70    snapshot_seqs: Arc<RwLock<HashMap<u64, u64>>>,
71    /// Mappings of the RegionId to the minimal sequence of SST file to scan.
72    sst_min_sequences: Arc<RwLock<HashMap<u64, u64>>>,
73    // we use Arc<RwLock>> for modifiable fields
74    #[builder(default)]
75    mutable_session_data: Arc<RwLock<MutableInner>>,
76    #[builder(default)]
77    mutable_query_context_data: Arc<RwLock<QueryContextMutableFields>>,
78    sql_dialect: Arc<dyn Dialect + Send + Sync>,
79    #[builder(default)]
80    extensions: HashMap<String, String>,
81    #[builder(setter(skip))]
82    query_options_snapshotted: bool,
83    /// The configuration parameter are used to store the parameters that are set by the user
84    #[builder(default)]
85    configuration_parameter: Arc<ConfigurationVariables>,
86    /// Local-only write batching selection; never transported in protobuf extensions.
87    #[builder(default)]
88    batching_enabled: bool,
89    /// Local-only opt-in for logical metric writes, independent of ordinary-table batching.
90    #[builder(default)]
91    logical_batching_enabled: bool,
92    /// Track which protocol the query comes from.
93    #[builder(default)]
94    channel: Channel,
95    /// Process-local admission for one database in this request. Never sent over the wire.
96    #[builder(setter(skip))]
97    admitted_write: Option<(String, String)>,
98    /// Process id for managing on-going queries
99    #[builder(default)]
100    process_id: u32,
101    /// Connection information
102    #[builder(default)]
103    conn_info: ConnInfo,
104    /// Protocol specific context
105    #[builder(default)]
106    protocol_ctx: ProtocolCtx,
107}
108
109/// This fields hold data that is only valid to current query context
110#[derive(Debug, Builder, Clone, Default)]
111pub struct QueryContextMutableFields {
112    warning: Option<String>,
113    // TODO: remove this when format is supported in datafusion
114    explain_format: Option<String>,
115    /// Explain options to control the verbose analyze output.
116    explain_options: Option<ExplainOptions>,
117}
118
119impl Display for QueryContext {
120    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
121        write!(
122            f,
123            "QueryContext{{catalog: {}, schema: {}}}",
124            self.current_catalog(),
125            self.current_schema()
126        )
127    }
128}
129
130impl QueryContextBuilder {
131    pub fn current_schema(mut self, schema: String) -> Self {
132        if self.mutable_session_data.is_none() {
133            self.mutable_session_data = Some(Arc::new(RwLock::new(MutableInner::default())));
134        }
135
136        // safe for unwrap because previous none check
137        self.mutable_session_data
138            .as_mut()
139            .unwrap()
140            .write()
141            .unwrap()
142            .schema = schema;
143        self
144    }
145
146    pub fn timezone(mut self, timezone: Timezone) -> Self {
147        if self.mutable_session_data.is_none() {
148            self.mutable_session_data = Some(Arc::new(RwLock::new(MutableInner::default())));
149        }
150
151        self.mutable_session_data
152            .as_mut()
153            .unwrap()
154            .write()
155            .unwrap()
156            .timezone = timezone;
157        self
158    }
159
160    pub fn explain_options(mut self, explain_options: Option<ExplainOptions>) -> Self {
161        self.mutable_query_context_data
162            .get_or_insert_default()
163            .write()
164            .unwrap()
165            .explain_options = explain_options;
166        self
167    }
168
169    pub fn skip_wal(mut self, skip_wal: bool) -> Self {
170        self.mutable_session_data
171            .get_or_insert_default()
172            .write()
173            .unwrap()
174            .skip_wal = skip_wal;
175        self
176    }
177
178    pub fn read_preference(mut self, read_preference: ReadPreference) -> Self {
179        self.mutable_session_data
180            .get_or_insert_default()
181            .write()
182            .unwrap()
183            .read_preference = read_preference;
184        self
185    }
186}
187
188impl TryFrom<&RegionRequestHeader> for QueryContext {
189    type Error = crate::session_config::Error;
190
191    fn try_from(value: &RegionRequestHeader) -> Result<Self, Self::Error> {
192        if let Some(ctx) = &value.query_context {
193            ctx.clone().try_into()
194        } else {
195            Ok(QueryContextBuilder::default()
196                .set_extension(
197                    REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
198                    generate_remote_query_id(),
199                )
200                .build())
201        }
202    }
203}
204
205impl TryFrom<api::v1::QueryContext> for QueryContext {
206    type Error = crate::session_config::Error;
207
208    fn try_from(mut ctx: api::v1::QueryContext) -> Result<Self, Self::Error> {
209        let read_preference = ctx.extensions.remove(READ_PREFERENCE_EXTENSION_KEY);
210        let read_preference = match read_preference {
211            Some(value) => ReadPreference::from_str(&value).map_err(|_| {
212                InvalidConfigValueSnafu {
213                    name: "read_preference",
214                    value,
215                    hint: "Expected a supported read preference",
216                }
217                .build()
218            })?,
219            None => ReadPreference::default(),
220        };
221        let sequences = ctx.snapshot_seqs.as_ref();
222        Ok(QueryContextBuilder::default()
223            .current_catalog(ctx.current_catalog)
224            .current_schema(ctx.current_schema)
225            .timezone(parse_timezone(Some(&ctx.timezone)))
226            .extensions(ctx.extensions)
227            .channel(ctx.channel.into())
228            .snapshot_seqs(Arc::new(RwLock::new(
229                sequences
230                    .map(|x| x.snapshot_seqs.clone())
231                    .unwrap_or_default(),
232            )))
233            .sst_min_sequences(Arc::new(RwLock::new(
234                sequences
235                    .map(|x| x.sst_min_sequences.clone())
236                    .unwrap_or_default(),
237            )))
238            .explain_options(ctx.explain)
239            .read_preference(read_preference)
240            .build())
241    }
242}
243
244impl From<QueryContext> for api::v1::QueryContext {
245    fn from(
246        QueryContext {
247            current_catalog,
248            mutable_session_data: mutable_inner,
249            extensions,
250            channel,
251            snapshot_seqs,
252            sst_min_sequences,
253            mutable_query_context_data,
254            ..
255        }: QueryContext,
256    ) -> Self {
257        let explain = mutable_query_context_data.read().unwrap().explain_options;
258        let mutable_inner = mutable_inner.read().unwrap();
259        let mut extensions = extensions;
260        extensions.remove(READ_PREFERENCE_EXTENSION_KEY);
261        if mutable_inner.read_preference != ReadPreference::Leader {
262            extensions.insert(
263                READ_PREFERENCE_EXTENSION_KEY.to_string(),
264                mutable_inner
265                    .read_preference
266                    .to_string()
267                    .to_ascii_lowercase(),
268            );
269        }
270        api::v1::QueryContext {
271            current_catalog,
272            current_schema: mutable_inner.schema.clone(),
273            timezone: mutable_inner.timezone.to_string(),
274            extensions,
275            channel: channel as u32,
276            snapshot_seqs: Some(api::v1::SnapshotSequences {
277                snapshot_seqs: snapshot_seqs.read().unwrap().clone(),
278                sst_min_sequences: sst_min_sequences.read().unwrap().clone(),
279            }),
280            explain,
281        }
282    }
283}
284
285impl From<&QueryContext> for api::v1::QueryContext {
286    fn from(ctx: &QueryContext) -> Self {
287        ctx.clone().into()
288    }
289}
290
291impl QueryContext {
292    /// Forks this context with an independent snapshot of mutable session data.
293    ///
294    /// Unlike [`Clone`], changes to the schema, user, timezone, and other fields
295    /// held in mutable session data do not affect this context.
296    pub fn fork(&self) -> Self {
297        let mut fork = self.clone();
298        fork.mutable_session_data = Arc::new(RwLock::new(
299            self.mutable_session_data.read().unwrap().clone(),
300        ));
301        fork
302    }
303
304    /// Forks a context for internal writes after admitting the complete request.
305    /// Call only after write admission succeeds for the current database.
306    pub fn with_write_admission(&self) -> Self {
307        let mut ctx = self.fork();
308        ctx.admitted_write = Some((ctx.current_catalog().to_string(), ctx.current_schema()));
309        ctx
310    }
311
312    /// Returns zero for writes covered by this request's database admission.
313    /// Usage accounting and the original protocol channel remain unchanged.
314    pub fn write_rows_to_admit(&self, catalog: &str, schema: &str, rows: u64) -> u64 {
315        if self
316            .admitted_write
317            .as_ref()
318            .is_some_and(|(c, s)| c == catalog && s == schema)
319        {
320            0
321        } else {
322            rows
323        }
324    }
325
326    pub fn arc() -> QueryContextRef {
327        Arc::new(
328            QueryContextBuilder::default()
329                .set_extension(
330                    REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
331                    generate_remote_query_id(),
332                )
333                .build(),
334        )
335    }
336
337    /// Create a new  datafusion's ConfigOptions instance based on the current QueryContext.
338    pub fn create_config_options(&self) -> ConfigOptions {
339        let mut config = ConfigOptions::default();
340        config.execution.time_zone = Some(self.timezone().to_string());
341        config
342    }
343
344    pub fn with(catalog: &str, schema: &str) -> QueryContext {
345        QueryContextBuilder::default()
346            .current_catalog(catalog.to_string())
347            .current_schema(schema.to_string())
348            .set_extension(
349                REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
350                generate_remote_query_id(),
351            )
352            .build()
353    }
354
355    pub fn with_channel(catalog: &str, schema: &str, channel: Channel) -> QueryContext {
356        QueryContextBuilder::default()
357            .current_catalog(catalog.to_string())
358            .current_schema(schema.to_string())
359            .channel(channel)
360            .set_extension(
361                REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
362                generate_remote_query_id(),
363            )
364            .build()
365    }
366
367    pub fn with_db_name(db_name: Option<&str>) -> QueryContext {
368        let (catalog, schema) = db_name
369            .map(|db| {
370                let (catalog, schema) = parse_catalog_and_schema_from_db_string(db);
371                (catalog, schema)
372            })
373            .unwrap_or_else(|| {
374                (
375                    DEFAULT_CATALOG_NAME.to_string(),
376                    DEFAULT_SCHEMA_NAME.to_string(),
377                )
378            });
379        QueryContextBuilder::default()
380            .current_catalog(catalog)
381            .current_schema(schema.clone())
382            .set_extension(
383                REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
384                generate_remote_query_id(),
385            )
386            .build()
387    }
388
389    pub fn current_schema(&self) -> String {
390        self.mutable_session_data.read().unwrap().schema.clone()
391    }
392
393    pub fn set_current_schema(&self, new_schema: &str) {
394        self.mutable_session_data.write().unwrap().schema = new_schema.to_string();
395    }
396
397    pub fn current_catalog(&self) -> &str {
398        &self.current_catalog
399    }
400
401    pub fn set_current_catalog(&mut self, new_catalog: &str) {
402        self.current_catalog = new_catalog.to_string();
403    }
404
405    pub fn sql_dialect(&self) -> &(dyn Dialect + Send + Sync) {
406        &*self.sql_dialect
407    }
408
409    pub fn get_db_string(&self) -> String {
410        let catalog = self.current_catalog();
411        let schema = self.current_schema();
412        build_db_string(catalog, &schema)
413    }
414
415    pub fn timezone(&self) -> Timezone {
416        self.mutable_session_data.read().unwrap().timezone.clone()
417    }
418
419    pub fn set_timezone(&self, timezone: Timezone) {
420        self.mutable_session_data.write().unwrap().timezone = timezone;
421    }
422
423    /// Returns whether ordinary inserts in this request should skip WAL.
424    pub fn skip_wal(&self) -> bool {
425        self.mutable_session_data.read().unwrap().skip_wal
426    }
427
428    pub fn set_skip_wal(&self, skip_wal: bool) {
429        self.mutable_session_data.write().unwrap().skip_wal = skip_wal;
430    }
431
432    pub fn read_preference(&self) -> ReadPreference {
433        self.mutable_session_data.read().unwrap().read_preference
434    }
435
436    pub fn set_read_preference(&self, read_preference: ReadPreference) {
437        self.mutable_session_data.write().unwrap().read_preference = read_preference;
438    }
439
440    /// Returns the latest procedure ID recorded in this Session.
441    pub fn last_procedure_id(&self) -> Option<String> {
442        self.mutable_session_data
443            .read()
444            .unwrap()
445            .last_procedure_id
446            .clone()
447    }
448
449    /// Records a procedure ID after successful statement execution and
450    /// construction of its ID result.
451    ///
452    /// Recording precedes `post_execute` hooks and protocol transmission, which
453    /// may still fail. It does not confirm that the client received the ID.
454    pub fn set_last_procedure_id(&self, procedure_id: String) {
455        self.mutable_session_data.write().unwrap().last_procedure_id = Some(procedure_id);
456    }
457
458    pub fn current_user(&self) -> UserInfoRef {
459        self.mutable_session_data.read().unwrap().user_info.clone()
460    }
461
462    pub fn set_current_user(&self, user: UserInfoRef) {
463        self.mutable_session_data.write().unwrap().user_info = user;
464    }
465
466    pub fn set_extension<S1: Into<String>, S2: Into<String>>(&mut self, key: S1, value: S2) {
467        self.extensions.insert(key.into(), value.into());
468    }
469
470    pub fn extension<S: AsRef<str>>(&self, key: S) -> Option<&str> {
471        self.extensions.get(key.as_ref()).map(|v| v.as_str())
472    }
473
474    pub fn remote_query_id(&self) -> Option<&str> {
475        self.extension(REMOTE_QUERY_ID_EXTENSION_KEY)
476    }
477
478    pub fn remote_query_id_value(&self) -> Option<QueryId> {
479        self.remote_query_id()
480            .and_then(|query_id| query_id.parse().ok())
481    }
482
483    pub fn enable_live_analyze_metrics(&mut self) {
484        if let Some(remote_query_id) = self.remote_query_id().map(str::to_string) {
485            self.set_extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY, remote_query_id);
486        }
487    }
488
489    pub fn live_analyze_metrics_enabled(&self) -> bool {
490        self.remote_query_id()
491            .zip(self.extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY))
492            .is_some_and(|(remote_query_id, value)| value == remote_query_id)
493    }
494
495    pub fn extensions(&self) -> HashMap<String, String> {
496        self.extensions.clone()
497    }
498
499    /// Returns normalized query options from the request over session defaults.
500    pub fn effective_query_options(
501        &self,
502    ) -> Result<HashMap<String, String>, crate::session_config::Error> {
503        let mut request_options = HashMap::new();
504        for (key, value) in &self.extensions {
505            if crate::hints::is_reserved_extension_key(key) {
506                continue;
507            }
508            // Older Frontends and Flownodes forward `query_parallelism=0` (their
509            // "use the server default" encoding) untouched inside the wire
510            // query context, so accept it as unset instead of failing the
511            // query on the Datanode side. The canonical
512            // `query.parallelism = 0` stays rejected.
513            if key.eq_ignore_ascii_case("query_parallelism") && value == "0" {
514                continue;
515            }
516            // Wire decoding preserves legacy frontend nonzero values; public entry points enforce the limit.
517            if let Some((canonical, normalized)) =
518                crate::query_options::parse_query_option(key, value, u16::MAX)?
519            {
520                if request_options
521                    .get(&canonical)
522                    .is_some_and(|previous| previous != &normalized)
523                {
524                    return crate::session_config::InvalidConfigValueSnafu {
525                        name: key,
526                        value,
527                        hint: "Conflicting aliases for the same query option",
528                    }
529                    .fail();
530                }
531                request_options.insert(canonical, normalized);
532            }
533        }
534        let mut effective = if self.query_options_snapshotted {
535            HashMap::new()
536        } else {
537            self.configuration_parameter.query_options()
538        };
539        effective.extend(request_options);
540        Ok(effective)
541    }
542
543    /// Creates a per-query immutable option snapshot while retaining shared mutable session data.
544    pub fn query_option_snapshot(&self) -> Result<Self, crate::session_config::Error> {
545        let mut snapshot = self.clone();
546        let options = snapshot.effective_query_options()?;
547        snapshot
548            .extensions
549            .retain(|key, _| crate::query_options::canonical_query_option_name(key).is_none());
550        // Older Datanodes only understand the legacy `query_parallelism` hint key, so
551        // mirror the canonical parallelism override for the wire format while keeping
552        // the canonical key for in-process consumers.
553        let legacy_parallelism = options
554            .get("query.parallelism")
555            .map(|parallelism| ("query_parallelism".to_string(), parallelism.clone()));
556        snapshot.extensions.extend(options);
557        if let Some((key, value)) = legacy_parallelism {
558            snapshot.extensions.entry(key).or_insert(value);
559        }
560        snapshot.query_options_snapshotted = true;
561        Ok(snapshot)
562    }
563
564    /// Default to double quote and fallback to back quote
565    pub fn quote_style(&self) -> char {
566        if self.sql_dialect().is_delimited_identifier_start('"') {
567            '"'
568        } else if self.sql_dialect().is_delimited_identifier_start('\'') {
569            '\''
570        } else {
571            '`'
572        }
573    }
574
575    pub fn configuration_parameter(&self) -> &ConfigurationVariables {
576        &self.configuration_parameter
577    }
578
579    /// Whether the local HTTP entry point selected logical-table batching.
580    pub fn logical_batching_enabled(&self) -> bool {
581        self.logical_batching_enabled
582    }
583
584    /// Sets local logical-table batching selection without adding a wire-visible extension.
585    pub fn set_logical_batching_enabled(&mut self, enabled: bool) {
586        self.logical_batching_enabled = enabled;
587    }
588
589    /// Whether the local protocol entry point selected ordinary-table batching.
590    pub fn batching_enabled(&self) -> bool {
591        self.batching_enabled
592    }
593
594    /// Sets local write batching selection without adding a wire-visible extension.
595    pub fn set_batching_enabled(&mut self, enabled: bool) {
596        self.batching_enabled = enabled;
597    }
598
599    pub fn channel(&self) -> Channel {
600        self.channel
601    }
602
603    pub fn set_channel(&mut self, channel: Channel) {
604        self.channel = channel;
605    }
606
607    pub fn warning(&self) -> Option<String> {
608        self.mutable_query_context_data
609            .read()
610            .unwrap()
611            .warning
612            .clone()
613    }
614
615    pub fn set_warning(&self, msg: String) {
616        self.mutable_query_context_data.write().unwrap().warning = Some(msg);
617    }
618
619    pub fn explain_format(&self) -> Option<String> {
620        self.mutable_query_context_data
621            .read()
622            .unwrap()
623            .explain_format
624            .clone()
625    }
626
627    pub fn set_explain_format(&self, format: String) {
628        self.mutable_query_context_data
629            .write()
630            .unwrap()
631            .explain_format = Some(format);
632    }
633
634    pub fn explain_verbose(&self) -> bool {
635        self.mutable_query_context_data
636            .read()
637            .unwrap()
638            .explain_options
639            .map(|opts| opts.verbose)
640            .unwrap_or(false)
641    }
642
643    pub fn set_explain_verbose(&self, verbose: bool) {
644        self.mutable_query_context_data
645            .write()
646            .unwrap()
647            .explain_options
648            .get_or_insert_default()
649            .verbose = verbose;
650    }
651
652    pub fn query_timeout(&self) -> Option<Duration> {
653        self.mutable_session_data.read().unwrap().query_timeout
654    }
655
656    pub fn query_timeout_as_millis(&self) -> u128 {
657        let timeout = self.mutable_session_data.read().unwrap().query_timeout;
658        if let Some(t) = timeout {
659            return t.as_millis();
660        }
661        0
662    }
663
664    pub fn set_query_timeout(&self, timeout: Duration) {
665        self.mutable_session_data.write().unwrap().query_timeout = Some(timeout);
666    }
667
668    pub fn insert_cursor(&self, name: String, rb: RecordBatchStreamCursor) {
669        let mut guard = self.mutable_session_data.write().unwrap();
670        guard.cursors.insert(name, Arc::new(rb));
671
672        let cursor_count = guard.cursors.len();
673        if cursor_count > CURSOR_COUNT_WARNING_LIMIT {
674            warn!("Current connection has {} open cursors", cursor_count);
675        }
676    }
677
678    pub fn remove_cursor(&self, name: &str) {
679        let mut guard = self.mutable_session_data.write().unwrap();
680        guard.cursors.remove(name);
681    }
682
683    pub fn get_cursor(&self, name: &str) -> Option<Arc<RecordBatchStreamCursor>> {
684        let guard = self.mutable_session_data.read().unwrap();
685        let rb = guard.cursors.get(name);
686        rb.cloned()
687    }
688
689    pub fn snapshots(&self) -> HashMap<u64, u64> {
690        self.snapshot_seqs.read().unwrap().clone()
691    }
692
693    pub fn sst_min_sequences(&self) -> HashMap<u64, u64> {
694        self.sst_min_sequences.read().unwrap().clone()
695    }
696
697    pub fn get_snapshot(&self, region_id: u64) -> Option<u64> {
698        self.snapshot_seqs.read().unwrap().get(&region_id).cloned()
699    }
700
701    pub fn set_snapshot(&self, region_id: u64, sequence: u64) {
702        self.snapshot_seqs
703            .write()
704            .unwrap()
705            .insert(region_id, sequence);
706    }
707
708    /// Returns `true` if the session can cast strings to numbers in MySQL style.
709    pub fn auto_string_to_numeric(&self) -> bool {
710        matches!(self.channel, Channel::Mysql)
711    }
712
713    /// Finds the minimal sequence of SST files to scan of a Region.
714    pub fn sst_min_sequence(&self, region_id: u64) -> Option<u64> {
715        self.sst_min_sequences
716            .read()
717            .unwrap()
718            .get(&region_id)
719            .copied()
720    }
721
722    pub fn process_id(&self) -> u32 {
723        self.process_id
724    }
725
726    /// Get client information
727    pub fn conn_info(&self) -> &ConnInfo {
728        &self.conn_info
729    }
730
731    pub fn protocol_ctx(&self) -> &ProtocolCtx {
732        &self.protocol_ctx
733    }
734
735    pub fn set_protocol_ctx(&mut self, protocol_ctx: ProtocolCtx) {
736        self.protocol_ctx = protocol_ctx;
737    }
738}
739
740impl QueryContextBuilder {
741    pub fn build(self) -> QueryContext {
742        let channel = self.channel.unwrap_or_default();
743        let mut extensions = self.extensions.unwrap_or_default();
744        extensions
745            .entry(REMOTE_QUERY_ID_EXTENSION_KEY.to_string())
746            .or_insert_with(generate_remote_query_id);
747        QueryContext {
748            current_catalog: self
749                .current_catalog
750                .unwrap_or_else(|| DEFAULT_CATALOG_NAME.to_string()),
751            snapshot_seqs: self.snapshot_seqs.unwrap_or_default(),
752            sst_min_sequences: self.sst_min_sequences.unwrap_or_default(),
753            mutable_session_data: self.mutable_session_data.unwrap_or_default(),
754            mutable_query_context_data: self.mutable_query_context_data.unwrap_or_default(),
755            sql_dialect: self
756                .sql_dialect
757                .unwrap_or_else(|| Arc::new(GreptimeDbDialect {})),
758            extensions,
759            query_options_snapshotted: false,
760            configuration_parameter: self
761                .configuration_parameter
762                .unwrap_or_else(|| Arc::new(ConfigurationVariables::default())),
763            channel,
764            batching_enabled: self.batching_enabled.unwrap_or_default(),
765            admitted_write: None,
766            logical_batching_enabled: self.logical_batching_enabled.unwrap_or_default(),
767            process_id: self.process_id.unwrap_or_default(),
768            conn_info: self.conn_info.unwrap_or_default(),
769            protocol_ctx: self.protocol_ctx.unwrap_or_default(),
770        }
771    }
772
773    pub fn set_extension(mut self, key: String, value: String) -> Self {
774        self.extensions
775            .get_or_insert_with(HashMap::new)
776            .insert(key, value);
777        self
778    }
779}
780
781#[derive(Debug, Clone, Default)]
782pub struct ConnInfo {
783    pub client_addr: Option<SocketAddr>,
784    pub channel: Channel,
785}
786
787impl Display for ConnInfo {
788    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
789        write!(
790            f,
791            "{}[{}]",
792            self.channel,
793            self.client_addr
794                .map(|addr| addr.to_string())
795                .as_deref()
796                .unwrap_or("unknown client addr")
797        )
798    }
799}
800
801impl ConnInfo {
802    pub fn new(client_addr: Option<SocketAddr>, channel: Channel) -> Self {
803        Self {
804            client_addr,
805            channel,
806        }
807    }
808}
809
810/// Returns the SQL dialect for the given query channel.
811pub fn dialect_for_channel(channel: Channel) -> Arc<dyn Dialect + Send + Sync> {
812    match channel {
813        Channel::Mysql => Arc::new(MySqlDialect {}),
814        Channel::Postgres => Arc::new(PostgreSqlDialect {}),
815        _ => Arc::new(GenericDialect {}),
816    }
817}
818
819#[derive(Default, Debug)]
820pub struct ConfigurationVariables {
821    postgres_bytea_output: ArcSwap<PGByteaOutputValue>,
822    pg_datestyle_format: ArcSwap<(PGDateTimeStyle, PGDateOrder)>,
823    pg_intervalstyle_format: ArcSwap<PGIntervalStyle>,
824    query_options: RwLock<HashMap<String, String>>,
825}
826
827impl Clone for ConfigurationVariables {
828    fn clone(&self) -> Self {
829        Self {
830            postgres_bytea_output: ArcSwap::new(self.postgres_bytea_output.load().clone()),
831            pg_datestyle_format: ArcSwap::new(self.pg_datestyle_format.load().clone()),
832            pg_intervalstyle_format: ArcSwap::new(self.pg_intervalstyle_format.load().clone()),
833            query_options: RwLock::new(self.query_options.read().unwrap().clone()),
834        }
835    }
836}
837
838impl ConfigurationVariables {
839    pub fn new() -> Self {
840        Self::default()
841    }
842
843    pub fn set_postgres_bytea_output(&self, value: PGByteaOutputValue) {
844        let _ = self.postgres_bytea_output.swap(Arc::new(value));
845    }
846
847    pub fn postgres_bytea_output(&self) -> Arc<PGByteaOutputValue> {
848        self.postgres_bytea_output.load().clone()
849    }
850
851    pub fn pg_datetime_style(&self) -> Arc<(PGDateTimeStyle, PGDateOrder)> {
852        self.pg_datestyle_format.load().clone()
853    }
854
855    pub fn set_pg_datetime_style(&self, style: PGDateTimeStyle, order: PGDateOrder) {
856        self.pg_datestyle_format.swap(Arc::new((style, order)));
857    }
858
859    pub fn pg_intervalstyle_format(&self) -> Arc<PGIntervalStyle> {
860        self.pg_intervalstyle_format.load().clone()
861    }
862
863    pub fn set_pg_intervalstyle_format(&self, value: PGIntervalStyle) {
864        self.pg_intervalstyle_format.swap(Arc::new(value));
865    }
866
867    pub fn allow_query_fallback(&self) -> bool {
868        self.query_options().get("query.allow_query_fallback") == Some(&"true".to_string())
869    }
870
871    pub fn set_allow_query_fallback(&self, allow: bool) {
872        self.query_options
873            .write()
874            .unwrap()
875            .insert("query.allow_query_fallback".to_string(), allow.to_string());
876    }
877
878    /// Validates and stores one canonicalized per-session query option.
879    pub fn set_query_option(
880        &self,
881        key: &str,
882        value: &str,
883    ) -> Result<(), crate::session_config::Error> {
884        let (canonical, normalized) = crate::query_options::parse_query_option(
885            key,
886            value,
887            crate::query_options::MAX_PUBLIC_PARALLELISM,
888        )?
889        .ok_or_else(|| crate::session_config::Error::InvalidConfigValue {
890            name: key.to_string(),
891            value: value.to_string(),
892            hint: "Not a supported query option".to_string(),
893            location: snafu::Location::new(file!(), line!(), column!()),
894        })?;
895        self.query_options
896            .write()
897            .unwrap()
898            .insert(canonical, normalized);
899        Ok(())
900    }
901
902    /// Returns the session's canonical query option overrides.
903    pub fn query_options(&self) -> HashMap<String, String> {
904        self.query_options.read().unwrap().clone()
905    }
906}
907
908#[cfg(test)]
909mod test {
910    use std::collections::HashMap;
911
912    use common_catalog::consts::DEFAULT_CATALOG_NAME;
913
914    use crate::Session;
915    use crate::context::{Channel, *};
916
917    #[test]
918    fn test_query_parallelism_wire_accepts_legacy_value() {
919        let mut context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
920        context.set_extension("query_parallelism", "2048");
921
922        assert_eq!(
923            context
924                .effective_query_options()
925                .unwrap()
926                .get("query.parallelism"),
927            Some(&"2048".to_string())
928        );
929    }
930
931    #[test]
932    fn test_set_query_parallelism_public_limit() {
933        let context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
934        assert!(
935            context
936                .configuration_parameter()
937                .set_query_option("query.parallelism", "1025")
938                .is_err()
939        );
940        assert!(
941            context
942                .configuration_parameter()
943                .set_query_option("query.parallelism", "1024")
944                .is_ok()
945        );
946    }
947
948    #[test]
949    fn test_session() {
950        let session = Session::new(
951            Some("127.0.0.1:9000".parse().unwrap()),
952            Channel::Mysql,
953            Default::default(),
954            100,
955        );
956        // test user_info
957        assert_eq!(session.user_info().username(), "greptime");
958
959        // test channel
960        assert_eq!(session.conn_info().channel, Channel::Mysql);
961        let client_addr = session.conn_info().client_addr.as_ref().unwrap();
962        assert_eq!(client_addr.ip().to_string(), "127.0.0.1");
963        assert_eq!(client_addr.port(), 9000);
964
965        assert_eq!("mysql[127.0.0.1:9000]", session.conn_info().to_string());
966        assert_eq!(100, session.process_id());
967
968        let query_ctx = session.new_query_context();
969        assert!(query_ctx.remote_query_id().is_some());
970    }
971
972    #[test]
973    fn test_context_db_string() {
974        let context = QueryContext::with("a0b1c2d3", "test");
975        assert_eq!("a0b1c2d3-test", context.get_db_string());
976
977        let context = QueryContext::with(DEFAULT_CATALOG_NAME, "test");
978        assert_eq!("test", context.get_db_string());
979    }
980
981    #[test]
982    fn test_fork_has_independent_mutable_session_data() {
983        let context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
984        let fork = context.fork();
985
986        fork.set_current_schema("private");
987
988        assert_eq!(context.current_schema(), "public");
989        assert_eq!(fork.current_schema(), "private");
990    }
991
992    #[test]
993    fn test_skip_wal_default_builder_and_fork() {
994        let default_context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
995        assert!(!default_context.skip_wal());
996        assert!(!QueryContextBuilder::default().build().skip_wal());
997        let context = QueryContextBuilder::default().skip_wal(true).build();
998        assert!(context.skip_wal());
999        let fork = context.fork();
1000        assert!(fork.skip_wal());
1001        fork.set_skip_wal(false);
1002        assert!(context.skip_wal());
1003        assert!(!fork.skip_wal());
1004        context.set_skip_wal(false);
1005        fork.set_skip_wal(true);
1006        assert!(!context.skip_wal());
1007        assert!(fork.skip_wal());
1008    }
1009
1010    #[test]
1011    fn test_write_admission_is_local_and_database_scoped() {
1012        let ctx = QueryContext::with_channel("greptime", "public", Channel::Otlp);
1013        let admitted = ctx.with_write_admission();
1014        assert_eq!(ctx.write_rows_to_admit("greptime", "public", 100), 100);
1015        assert_eq!(admitted.write_rows_to_admit("greptime", "public", 100), 0);
1016        assert_eq!(admitted.write_rows_to_admit("greptime", "other", 100), 100);
1017        assert_eq!(admitted.write_rows_to_admit("other", "public", 100), 100);
1018        assert_eq!(admitted.channel(), Channel::Otlp);
1019        assert_eq!(
1020            admitted
1021                .fork()
1022                .write_rows_to_admit("greptime", "public", 100),
1023            0
1024        );
1025        let wire: api::v1::QueryContext = admitted.into();
1026        let restored = QueryContext::try_from(wire).unwrap();
1027        assert_eq!(restored.write_rows_to_admit("greptime", "public", 100), 100);
1028    }
1029
1030    #[test]
1031    fn test_skip_wal_is_not_serialized_in_query_context() {
1032        let context = QueryContextBuilder::default().skip_wal(true).build();
1033        let api_context: api::v1::QueryContext = context.into();
1034        assert!(
1035            !api_context
1036                .extensions
1037                .contains_key(crate::hints::INSERT_SKIP_WAL_HINT)
1038        );
1039        let restored: QueryContext = api_context.try_into().unwrap();
1040        assert!(!restored.skip_wal());
1041    }
1042
1043    #[test]
1044    fn test_api_query_context_roundtrip_with_sequences() {
1045        let api_ctx = api::v1::QueryContext {
1046            current_catalog: "c1".to_string(),
1047            current_schema: "s1".to_string(),
1048            timezone: "UTC".to_string(),
1049            extensions: HashMap::from([("flow.return_region_seq".to_string(), "true".to_string())]),
1050            channel: Channel::Internal as u32,
1051            snapshot_seqs: Some(api::v1::SnapshotSequences {
1052                snapshot_seqs: HashMap::from([(1, 100)]),
1053                sst_min_sequences: HashMap::from([(1, 90)]),
1054            }),
1055            explain: None,
1056        };
1057
1058        let session_ctx: QueryContext = api_ctx.clone().try_into().unwrap();
1059        let roundtrip_api: api::v1::QueryContext = session_ctx.into();
1060
1061        assert_eq!(roundtrip_api.current_catalog, api_ctx.current_catalog);
1062        assert_eq!(roundtrip_api.current_schema, api_ctx.current_schema);
1063        assert_eq!(roundtrip_api.timezone, api_ctx.timezone);
1064        assert_eq!(
1065            roundtrip_api.extensions.get("flow.return_region_seq"),
1066            Some(&"true".to_string())
1067        );
1068        assert!(
1069            roundtrip_api
1070                .extensions
1071                .contains_key(REMOTE_QUERY_ID_EXTENSION_KEY)
1072        );
1073        assert_eq!(roundtrip_api.channel, api_ctx.channel);
1074        assert_eq!(roundtrip_api.snapshot_seqs, api_ctx.snapshot_seqs);
1075    }
1076
1077    #[test]
1078    fn test_query_context_remote_query_id_round_trip() {
1079        let query_id = "0195f4fd-c503-7c54-8b8f-7dfb8f6f9c4a";
1080        let ctx = QueryContextBuilder::default()
1081            .current_catalog(DEFAULT_CATALOG_NAME.to_string())
1082            .current_schema("public".to_string())
1083            .set_extension(
1084                REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
1085                query_id.to_string(),
1086            )
1087            .build();
1088
1089        assert_eq!(ctx.remote_query_id(), Some(query_id));
1090        assert_eq!(ctx.remote_query_id_value().unwrap().to_string(), query_id);
1091
1092        let proto: api::v1::QueryContext = (&ctx).into();
1093        let restored = QueryContext::try_from(proto).unwrap();
1094        assert_eq!(restored.remote_query_id(), Some(query_id));
1095        assert_eq!(
1096            restored.remote_query_id_value().unwrap().to_string(),
1097            query_id
1098        );
1099    }
1100
1101    #[test]
1102    fn test_query_context_read_preference_wire_values() {
1103        let wire = |value: Option<&str>| api::v1::QueryContext {
1104            current_catalog: DEFAULT_CATALOG_NAME.to_string(),
1105            current_schema: DEFAULT_SCHEMA_NAME.to_string(),
1106            timezone: "UTC".to_string(),
1107            extensions: value
1108                .map(|value| {
1109                    HashMap::from([(READ_PREFERENCE_EXTENSION_KEY.to_string(), value.to_string())])
1110                })
1111                .unwrap_or_default(),
1112            channel: Channel::Internal as u32,
1113            snapshot_seqs: None,
1114            explain: None,
1115        };
1116
1117        let header = RegionRequestHeader::default();
1118        let header_context = QueryContext::try_from(&header).unwrap();
1119        assert_eq!(header_context.read_preference(), ReadPreference::Leader);
1120
1121        for value in [None, Some("leader"), Some("LEADER")] {
1122            let ctx = QueryContext::try_from(wire(value)).unwrap();
1123            assert_eq!(ctx.read_preference(), ReadPreference::Leader);
1124            assert!(!ctx.extensions().contains_key(READ_PREFERENCE_EXTENSION_KEY));
1125        }
1126        for value in ["", "unknown"] {
1127            let error = QueryContext::try_from(wire(Some(value))).unwrap_err();
1128            assert!(matches!(
1129                error,
1130                crate::session_config::Error::InvalidConfigValue {
1131                    name,
1132                    value: actual,
1133                    ..
1134                } if name == "read_preference" && actual == value
1135            ));
1136        }
1137    }
1138
1139    #[test]
1140    fn test_legacy_query_context_wire_defaults_to_leader() {
1141        use prost::Message;
1142
1143        let legacy = api::v1::QueryContext::decode(
1144            include_bytes!(
1145                "../../../tests/compatibility/wire/read_preference/legacy_query_context.pb"
1146            )
1147            .as_slice(),
1148        )
1149        .unwrap();
1150        assert_eq!(legacy.current_catalog, "c1");
1151        assert_eq!(legacy.current_schema, "s1");
1152        assert_eq!(legacy.timezone, "UTC");
1153        assert_eq!(legacy.channel, Channel::Internal as u32);
1154        assert_eq!(
1155            legacy
1156                .extensions
1157                .get("flow.return_region_seq")
1158                .map(String::as_str),
1159            Some("true")
1160        );
1161        assert!(
1162            !legacy
1163                .extensions
1164                .contains_key(READ_PREFERENCE_EXTENSION_KEY)
1165        );
1166
1167        let restored = QueryContext::try_from(legacy).unwrap();
1168        assert_eq!(restored.read_preference(), ReadPreference::Leader);
1169        assert_eq!(restored.current_catalog(), "c1");
1170        assert_eq!(restored.current_schema(), "s1");
1171        assert_eq!(restored.timezone().to_string(), "UTC");
1172        assert_eq!(restored.channel(), Channel::Internal);
1173        assert_eq!(restored.extension("flow.return_region_seq"), Some("true"));
1174
1175        let outbound: api::v1::QueryContext = restored.into();
1176        let roundtrip = api::v1::QueryContext::decode(outbound.encode_to_vec().as_slice()).unwrap();
1177        assert_eq!(roundtrip.current_catalog, "c1");
1178        assert_eq!(roundtrip.current_schema, "s1");
1179        assert_eq!(roundtrip.timezone, "UTC");
1180        assert_eq!(roundtrip.channel, Channel::Internal as u32);
1181        assert_eq!(
1182            roundtrip
1183                .extensions
1184                .get("flow.return_region_seq")
1185                .map(String::as_str),
1186            Some("true")
1187        );
1188        assert!(
1189            !roundtrip
1190                .extensions
1191                .contains_key(READ_PREFERENCE_EXTENSION_KEY)
1192        );
1193    }
1194
1195    #[test]
1196    fn test_outbound_read_preference_clears_stale_extension() {
1197        let context = QueryContextBuilder::default()
1198            .set_extension(
1199                READ_PREFERENCE_EXTENSION_KEY.to_string(),
1200                "stale".to_string(),
1201            )
1202            .set_extension("unrelated".to_string(), "preserved".to_string())
1203            .build();
1204        let wire: api::v1::QueryContext = context.into();
1205        assert!(!wire.extensions.contains_key(READ_PREFERENCE_EXTENSION_KEY));
1206        assert_eq!(
1207            wire.extensions.get("unrelated").map(String::as_str),
1208            Some("preserved")
1209        );
1210    }
1211
1212    #[test]
1213    fn test_live_analyze_metrics_requires_matching_remote_query_id() {
1214        let mut ctx = QueryContext::arc().as_ref().clone();
1215        assert!(!ctx.live_analyze_metrics_enabled());
1216
1217        ctx.enable_live_analyze_metrics();
1218        assert!(ctx.live_analyze_metrics_enabled());
1219
1220        ctx.set_extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY, "true");
1221        assert!(!ctx.live_analyze_metrics_enabled());
1222
1223        ctx.set_extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY, "another-query-id");
1224        assert!(!ctx.live_analyze_metrics_enabled());
1225    }
1226    #[test]
1227    fn test_batching_selection_is_local_only() {
1228        let mut ctx = QueryContextBuilder::default().build();
1229        assert!(!ctx.batching_enabled());
1230        assert!(!ctx.logical_batching_enabled());
1231        ctx.set_logical_batching_enabled(true);
1232        assert!(ctx.clone().logical_batching_enabled());
1233        assert!(ctx.fork().logical_batching_enabled());
1234        ctx.set_batching_enabled(true);
1235        assert!(ctx.clone().batching_enabled());
1236        assert!(ctx.fork().batching_enabled());
1237        let wire: api::v1::QueryContext = ctx.into();
1238        let restored = QueryContext::try_from(wire).unwrap();
1239        assert!(!restored.batching_enabled());
1240        assert!(!restored.logical_batching_enabled());
1241        let ctx = QueryContextBuilder::default()
1242            .set_extension("batching_enabled".to_string(), "true".to_string())
1243            .build();
1244        assert!(!ctx.batching_enabled());
1245    }
1246}