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