1use std::collections::HashMap;
16use std::fmt::{Display, Formatter};
17use std::net::SocketAddr;
18use std::str::FromStr;
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::sync::{Arc, RwLock, Weak};
21use std::time::Duration;
22
23use api::v1::ExplainOptions;
24use api::v1::region::RegionRequestHeader;
25use arc_swap::ArcSwap;
26use auth::UserInfoRef;
27pub use common_base::protocol::Channel;
28use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
29use common_catalog::{build_db_string, parse_catalog_and_schema_from_db_string};
30use common_recordbatch::cursor::RecordBatchStreamCursor;
31use common_telemetry::warn;
32use common_time::Timezone;
33use common_time::timezone::parse_timezone;
34use datafusion_common::config::ConfigOptions;
35use derive_builder::Builder;
36use sql::dialect::{Dialect, GenericDialect, GreptimeDbDialect, MySqlDialect, PostgreSqlDialect};
37
38pub use crate::hints::{
39 LIVE_ANALYZE_METRICS_EXTENSION_KEY, READ_PREFERENCE_EXTENSION_KEY,
40 REMOTE_QUERY_ID_EXTENSION_KEY, SUPPORT_FLIGHT_METRICS_BEFORE_BATCH_EXTENSION_KEY,
41};
42use crate::protocol_ctx::ProtocolCtx;
43use crate::query_id::QueryId;
44use crate::session_config::{
45 InvalidConfigValueSnafu, PGByteaOutputValue, PGDateOrder, PGDateTimeStyle, PGIntervalStyle,
46};
47use crate::write_progress::WriteProgress;
48use crate::{MutableInner, ReadPreference};
49
50#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub enum MetricDiscoveryScope {
55 #[default]
57 Unavailable,
58 Unrestricted,
60 Allowed(std::collections::HashSet<auth::PermissionTableTarget>),
62}
63
64impl MetricDiscoveryScope {
65 pub fn allowed(targets: impl IntoIterator<Item = (String, String, String)>) -> Self {
66 Self::Allowed(
67 targets
68 .into_iter()
69 .map(|(catalog, schema, table)| {
70 auth::PermissionTableTarget::new(catalog, schema, table)
71 })
72 .collect(),
73 )
74 }
75}
76
77pub type QueryContextRef = Arc<QueryContext>;
78pub type ConnInfoRef = Arc<ConnInfo>;
79
80pub const FLIGHT_METRICS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
81
82const CURSOR_COUNT_WARNING_LIMIT: usize = 10;
83
84pub fn generate_remote_query_id() -> String {
85 generate_remote_query_id_value().to_string()
86}
87
88pub fn generate_remote_query_id_value() -> QueryId {
89 QueryId::new()
90}
91
92#[derive(Debug, Builder, Clone)]
93#[builder(pattern = "owned")]
94#[builder(build_fn(skip))]
95pub struct QueryContext {
96 current_catalog: String,
97 snapshot_seqs: Arc<RwLock<HashMap<u64, u64>>>,
100 sst_min_sequences: Arc<RwLock<HashMap<u64, u64>>>,
102 #[builder(default)]
104 mutable_session_data: Arc<RwLock<MutableInner>>,
105 #[builder(default)]
106 mutable_query_context_data: Arc<RwLock<QueryContextMutableFields>>,
107 sql_dialect: Arc<dyn Dialect + Send + Sync>,
108 #[builder(default)]
109 extensions: HashMap<String, String>,
110 #[builder(setter(skip))]
111 query_options_snapshotted: bool,
112 #[builder(default)]
114 configuration_parameter: Arc<ConfigurationVariables>,
115 #[builder(default)]
117 batching_enabled: bool,
118 #[builder(default)]
120 logical_batching_enabled: bool,
121 #[builder(default)]
123 channel: Channel,
124 #[builder(setter(skip))]
126 admitted_write: Option<(String, String)>,
127 #[builder(setter(skip))]
129 write_progress: Option<Arc<WriteProgress>>,
130 #[builder(setter(skip))]
132 body_memory_bytes: Weak<AtomicU64>,
133 #[builder(setter(skip))]
135 confirmed_writes: bool,
136 #[builder(default)]
138 process_id: u32,
139 #[builder(default)]
141 conn_info: ConnInfo,
142 #[builder(default)]
144 protocol_ctx: ProtocolCtx,
145 #[builder(setter(skip))]
148 metric_discovery_scope: MetricDiscoveryScope,
149}
150
151impl QueryContext {
152 pub fn metric_discovery_scope(&self) -> &MetricDiscoveryScope {
154 &self.metric_discovery_scope
155 }
156
157 pub fn set_metric_discovery_scope(&mut self, scope: MetricDiscoveryScope) {
159 self.metric_discovery_scope = scope;
160 }
161}
162
163#[derive(Debug, Builder, Clone, Default)]
165pub struct QueryContextMutableFields {
166 warning: Option<String>,
167 explain_format: Option<String>,
169 explain_options: Option<ExplainOptions>,
171}
172
173impl Display for QueryContext {
174 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
175 write!(
176 f,
177 "QueryContext{{catalog: {}, schema: {}}}",
178 self.current_catalog(),
179 self.current_schema()
180 )
181 }
182}
183
184impl QueryContextBuilder {
185 pub fn current_schema(mut self, schema: String) -> Self {
186 if self.mutable_session_data.is_none() {
187 self.mutable_session_data = Some(Arc::new(RwLock::new(MutableInner::default())));
188 }
189
190 self.mutable_session_data
192 .as_mut()
193 .unwrap()
194 .write()
195 .unwrap()
196 .schema = schema;
197 self
198 }
199
200 pub fn timezone(mut self, timezone: Timezone) -> Self {
201 if self.mutable_session_data.is_none() {
202 self.mutable_session_data = Some(Arc::new(RwLock::new(MutableInner::default())));
203 }
204
205 self.mutable_session_data
206 .as_mut()
207 .unwrap()
208 .write()
209 .unwrap()
210 .timezone = timezone;
211 self
212 }
213
214 pub fn explain_options(mut self, explain_options: Option<ExplainOptions>) -> Self {
215 self.mutable_query_context_data
216 .get_or_insert_default()
217 .write()
218 .unwrap()
219 .explain_options = explain_options;
220 self
221 }
222
223 pub fn skip_wal(mut self, skip_wal: bool) -> Self {
224 self.mutable_session_data
225 .get_or_insert_default()
226 .write()
227 .unwrap()
228 .skip_wal = skip_wal;
229 self
230 }
231
232 pub fn read_preference(mut self, read_preference: ReadPreference) -> Self {
233 self.mutable_session_data
234 .get_or_insert_default()
235 .write()
236 .unwrap()
237 .read_preference = read_preference;
238 self
239 }
240}
241
242impl TryFrom<&RegionRequestHeader> for QueryContext {
243 type Error = crate::session_config::Error;
244
245 fn try_from(value: &RegionRequestHeader) -> Result<Self, Self::Error> {
246 if let Some(ctx) = &value.query_context {
247 ctx.clone().try_into()
248 } else {
249 Ok(QueryContextBuilder::default()
250 .set_extension(
251 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
252 generate_remote_query_id(),
253 )
254 .build())
255 }
256 }
257}
258
259impl TryFrom<api::v1::QueryContext> for QueryContext {
260 type Error = crate::session_config::Error;
261
262 fn try_from(mut ctx: api::v1::QueryContext) -> Result<Self, Self::Error> {
263 let read_preference = ctx.extensions.remove(READ_PREFERENCE_EXTENSION_KEY);
264 let read_preference = match read_preference {
265 Some(value) => ReadPreference::from_str(&value).map_err(|_| {
266 InvalidConfigValueSnafu {
267 name: "read_preference",
268 value,
269 hint: "Expected a supported read preference",
270 }
271 .build()
272 })?,
273 None => ReadPreference::default(),
274 };
275 let sequences = ctx.snapshot_seqs.as_ref();
276 Ok(QueryContextBuilder::default()
277 .current_catalog(ctx.current_catalog)
278 .current_schema(ctx.current_schema)
279 .timezone(parse_timezone(Some(&ctx.timezone)))
280 .extensions(ctx.extensions)
281 .channel(ctx.channel.into())
282 .snapshot_seqs(Arc::new(RwLock::new(
283 sequences
284 .map(|x| x.snapshot_seqs.clone())
285 .unwrap_or_default(),
286 )))
287 .sst_min_sequences(Arc::new(RwLock::new(
288 sequences
289 .map(|x| x.sst_min_sequences.clone())
290 .unwrap_or_default(),
291 )))
292 .explain_options(ctx.explain)
293 .read_preference(read_preference)
294 .build())
295 }
296}
297
298impl From<QueryContext> for api::v1::QueryContext {
299 fn from(
300 QueryContext {
301 current_catalog,
302 mutable_session_data: mutable_inner,
303 extensions,
304 channel,
305 snapshot_seqs,
306 sst_min_sequences,
307 mutable_query_context_data,
308 ..
309 }: QueryContext,
310 ) -> Self {
311 let explain = mutable_query_context_data.read().unwrap().explain_options;
312 let mutable_inner = mutable_inner.read().unwrap();
313 let mut extensions = extensions;
314 extensions.remove(READ_PREFERENCE_EXTENSION_KEY);
315 if mutable_inner.read_preference != ReadPreference::Leader {
316 extensions.insert(
317 READ_PREFERENCE_EXTENSION_KEY.to_string(),
318 mutable_inner
319 .read_preference
320 .to_string()
321 .to_ascii_lowercase(),
322 );
323 }
324 api::v1::QueryContext {
325 current_catalog,
326 current_schema: mutable_inner.schema.clone(),
327 timezone: mutable_inner.timezone.to_string(),
328 extensions,
329 channel: channel as u32,
330 snapshot_seqs: Some(api::v1::SnapshotSequences {
331 snapshot_seqs: snapshot_seqs.read().unwrap().clone(),
332 sst_min_sequences: sst_min_sequences.read().unwrap().clone(),
333 }),
334 explain,
335 }
336 }
337}
338
339impl From<&QueryContext> for api::v1::QueryContext {
340 fn from(ctx: &QueryContext) -> Self {
341 ctx.clone().into()
342 }
343}
344
345impl QueryContext {
346 pub fn write_progress(&self) -> Option<&Arc<WriteProgress>> {
347 self.write_progress.as_ref()
348 }
349
350 pub fn set_write_progress(&mut self, progress: Arc<WriteProgress>) {
351 self.write_progress = Some(progress);
352 }
353
354 pub fn set_body_memory_bytes(&mut self, bytes: Weak<AtomicU64>) {
356 self.body_memory_bytes = bytes;
357 }
358
359 pub fn held_memory_bytes(&self) -> u64 {
361 self.body_memory_bytes
362 .upgrade()
363 .map_or(0, |bytes| bytes.load(Ordering::Acquire))
364 .saturating_add(
365 self.write_progress
366 .as_ref()
367 .map_or(0, |progress| progress.reserved_bytes()),
368 )
369 }
370
371 pub fn with_confirmed_writes(&self) -> Self {
378 let mut ctx = self.fork();
379 ctx.confirmed_writes = true;
380 ctx
381 }
382
383 pub fn confirmed_writes(&self) -> bool {
386 self.confirmed_writes
387 }
388
389 pub fn fork(&self) -> Self {
394 let mut fork = self.clone();
395 fork.mutable_session_data = Arc::new(RwLock::new(
396 self.mutable_session_data.read().unwrap().clone(),
397 ));
398 fork
399 }
400
401 pub fn with_write_admission(&self) -> Self {
404 let mut ctx = self.fork();
405 ctx.admitted_write = Some((ctx.current_catalog().to_string(), ctx.current_schema()));
406 ctx
407 }
408
409 pub fn write_rows_to_admit(&self, catalog: &str, schema: &str, rows: u64) -> u64 {
412 if self
413 .admitted_write
414 .as_ref()
415 .is_some_and(|(c, s)| c == catalog && s == schema)
416 {
417 0
418 } else {
419 rows
420 }
421 }
422
423 pub fn arc() -> QueryContextRef {
424 Arc::new(
425 QueryContextBuilder::default()
426 .set_extension(
427 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
428 generate_remote_query_id(),
429 )
430 .build(),
431 )
432 }
433
434 pub fn create_config_options(&self) -> ConfigOptions {
436 let mut config = ConfigOptions::default();
437 config.execution.time_zone = Some(self.timezone().to_string());
438 config
439 }
440
441 pub fn with(catalog: &str, schema: &str) -> QueryContext {
442 QueryContextBuilder::default()
443 .current_catalog(catalog.to_string())
444 .current_schema(schema.to_string())
445 .set_extension(
446 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
447 generate_remote_query_id(),
448 )
449 .build()
450 }
451
452 pub fn with_channel(catalog: &str, schema: &str, channel: Channel) -> QueryContext {
453 QueryContextBuilder::default()
454 .current_catalog(catalog.to_string())
455 .current_schema(schema.to_string())
456 .channel(channel)
457 .set_extension(
458 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
459 generate_remote_query_id(),
460 )
461 .build()
462 }
463
464 pub fn with_db_name(db_name: Option<&str>) -> QueryContext {
465 let (catalog, schema) = db_name
466 .map(|db| {
467 let (catalog, schema) = parse_catalog_and_schema_from_db_string(db);
468 (catalog, schema)
469 })
470 .unwrap_or_else(|| {
471 (
472 DEFAULT_CATALOG_NAME.to_string(),
473 DEFAULT_SCHEMA_NAME.to_string(),
474 )
475 });
476 QueryContextBuilder::default()
477 .current_catalog(catalog)
478 .current_schema(schema.clone())
479 .set_extension(
480 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
481 generate_remote_query_id(),
482 )
483 .build()
484 }
485
486 pub fn current_schema(&self) -> String {
487 self.mutable_session_data.read().unwrap().schema.clone()
488 }
489
490 pub fn set_current_schema(&self, new_schema: &str) {
491 self.mutable_session_data.write().unwrap().schema = new_schema.to_string();
492 }
493
494 pub fn current_catalog(&self) -> &str {
495 &self.current_catalog
496 }
497
498 pub fn set_current_catalog(&mut self, new_catalog: &str) {
499 self.current_catalog = new_catalog.to_string();
500 }
501
502 pub fn sql_dialect(&self) -> &(dyn Dialect + Send + Sync) {
503 &*self.sql_dialect
504 }
505
506 pub fn get_db_string(&self) -> String {
507 let catalog = self.current_catalog();
508 let schema = self.current_schema();
509 build_db_string(catalog, &schema)
510 }
511
512 pub fn timezone(&self) -> Timezone {
513 self.mutable_session_data.read().unwrap().timezone.clone()
514 }
515
516 pub fn set_timezone(&self, timezone: Timezone) {
517 self.mutable_session_data.write().unwrap().timezone = timezone;
518 }
519
520 pub fn skip_wal(&self) -> bool {
522 self.mutable_session_data.read().unwrap().skip_wal
523 }
524
525 pub fn set_skip_wal(&self, skip_wal: bool) {
526 self.mutable_session_data.write().unwrap().skip_wal = skip_wal;
527 }
528
529 pub fn read_preference(&self) -> ReadPreference {
530 self.mutable_session_data.read().unwrap().read_preference
531 }
532
533 pub fn set_read_preference(&self, read_preference: ReadPreference) {
534 self.mutable_session_data.write().unwrap().read_preference = read_preference;
535 }
536
537 pub fn last_procedure_id(&self) -> Option<String> {
539 self.mutable_session_data
540 .read()
541 .unwrap()
542 .last_procedure_id
543 .clone()
544 }
545
546 pub fn set_last_procedure_id(&self, procedure_id: String) {
552 self.mutable_session_data.write().unwrap().last_procedure_id = Some(procedure_id);
553 }
554
555 pub fn current_user(&self) -> UserInfoRef {
556 self.mutable_session_data.read().unwrap().user_info.clone()
557 }
558
559 pub fn set_current_user(&self, user: UserInfoRef) {
560 self.mutable_session_data.write().unwrap().user_info = user;
561 }
562
563 pub fn set_extension<S1: Into<String>, S2: Into<String>>(&mut self, key: S1, value: S2) {
564 self.extensions.insert(key.into(), value.into());
565 }
566
567 pub fn extension<S: AsRef<str>>(&self, key: S) -> Option<&str> {
568 self.extensions.get(key.as_ref()).map(|v| v.as_str())
569 }
570
571 pub fn remote_query_id(&self) -> Option<&str> {
572 self.extension(REMOTE_QUERY_ID_EXTENSION_KEY)
573 }
574
575 pub fn remote_query_id_value(&self) -> Option<QueryId> {
576 self.remote_query_id()
577 .and_then(|query_id| query_id.parse().ok())
578 }
579
580 pub fn enable_live_analyze_metrics(&mut self) {
581 if let Some(remote_query_id) = self.remote_query_id().map(str::to_string) {
582 self.set_extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY, remote_query_id);
583 }
584 }
585
586 pub fn live_analyze_metrics_enabled(&self) -> bool {
587 self.remote_query_id()
588 .zip(self.extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY))
589 .is_some_and(|(remote_query_id, value)| value == remote_query_id)
590 }
591
592 pub fn extensions(&self) -> HashMap<String, String> {
593 self.extensions.clone()
594 }
595
596 pub fn effective_query_options(
598 &self,
599 ) -> Result<HashMap<String, String>, crate::session_config::Error> {
600 let mut request_options = HashMap::new();
601 for (key, value) in &self.extensions {
602 if crate::hints::is_reserved_extension_key(key) {
603 continue;
604 }
605 if key.eq_ignore_ascii_case("query_parallelism") && value == "0" {
611 continue;
612 }
613 if let Some((canonical, normalized)) =
615 crate::query_options::parse_query_option(key, value, u16::MAX)?
616 {
617 if request_options
618 .get(&canonical)
619 .is_some_and(|previous| previous != &normalized)
620 {
621 return crate::session_config::InvalidConfigValueSnafu {
622 name: key,
623 value,
624 hint: "Conflicting aliases for the same query option",
625 }
626 .fail();
627 }
628 request_options.insert(canonical, normalized);
629 }
630 }
631 let mut effective = if self.query_options_snapshotted {
632 HashMap::new()
633 } else {
634 self.configuration_parameter.query_options()
635 };
636 effective.extend(request_options);
637 Ok(effective)
638 }
639
640 pub fn query_option_snapshot(&self) -> Result<Self, crate::session_config::Error> {
642 let mut snapshot = self.clone();
643 let options = snapshot.effective_query_options()?;
644 snapshot
645 .extensions
646 .retain(|key, _| crate::query_options::canonical_query_option_name(key).is_none());
647 let legacy_parallelism = options
651 .get("query.parallelism")
652 .map(|parallelism| ("query_parallelism".to_string(), parallelism.clone()));
653 snapshot.extensions.extend(options);
654 if let Some((key, value)) = legacy_parallelism {
655 snapshot.extensions.entry(key).or_insert(value);
656 }
657 snapshot.query_options_snapshotted = true;
658 Ok(snapshot)
659 }
660
661 pub fn quote_style(&self) -> char {
663 if self.sql_dialect().is_delimited_identifier_start('"') {
664 '"'
665 } else if self.sql_dialect().is_delimited_identifier_start('\'') {
666 '\''
667 } else {
668 '`'
669 }
670 }
671
672 pub fn configuration_parameter(&self) -> &ConfigurationVariables {
673 &self.configuration_parameter
674 }
675
676 pub fn logical_batching_enabled(&self) -> bool {
678 self.logical_batching_enabled
679 }
680
681 pub fn set_logical_batching_enabled(&mut self, enabled: bool) {
683 self.logical_batching_enabled = enabled;
684 }
685
686 pub fn batching_enabled(&self) -> bool {
688 self.batching_enabled
689 }
690
691 pub fn set_batching_enabled(&mut self, enabled: bool) {
693 self.batching_enabled = enabled;
694 }
695
696 pub fn channel(&self) -> Channel {
697 self.channel
698 }
699
700 pub fn set_channel(&mut self, channel: Channel) {
701 self.channel = channel;
702 }
703
704 pub fn warning(&self) -> Option<String> {
705 self.mutable_query_context_data
706 .read()
707 .unwrap()
708 .warning
709 .clone()
710 }
711
712 pub fn set_warning(&self, msg: String) {
713 self.mutable_query_context_data.write().unwrap().warning = Some(msg);
714 }
715
716 pub fn explain_format(&self) -> Option<String> {
717 self.mutable_query_context_data
718 .read()
719 .unwrap()
720 .explain_format
721 .clone()
722 }
723
724 pub fn set_explain_format(&self, format: String) {
725 self.mutable_query_context_data
726 .write()
727 .unwrap()
728 .explain_format = Some(format);
729 }
730
731 pub fn explain_verbose(&self) -> bool {
732 self.mutable_query_context_data
733 .read()
734 .unwrap()
735 .explain_options
736 .map(|opts| opts.verbose)
737 .unwrap_or(false)
738 }
739
740 pub fn set_explain_verbose(&self, verbose: bool) {
741 self.mutable_query_context_data
742 .write()
743 .unwrap()
744 .explain_options
745 .get_or_insert_default()
746 .verbose = verbose;
747 }
748
749 pub fn query_timeout(&self) -> Option<Duration> {
750 self.mutable_session_data.read().unwrap().query_timeout
751 }
752
753 pub fn query_timeout_as_millis(&self) -> u128 {
754 let timeout = self.mutable_session_data.read().unwrap().query_timeout;
755 if let Some(t) = timeout {
756 return t.as_millis();
757 }
758 0
759 }
760
761 pub fn set_query_timeout(&self, timeout: Duration) {
762 self.mutable_session_data.write().unwrap().query_timeout = Some(timeout);
763 }
764
765 pub fn insert_cursor(&self, name: String, rb: RecordBatchStreamCursor) {
766 let mut guard = self.mutable_session_data.write().unwrap();
767 guard.cursors.insert(name, Arc::new(rb));
768
769 let cursor_count = guard.cursors.len();
770 if cursor_count > CURSOR_COUNT_WARNING_LIMIT {
771 warn!("Current connection has {} open cursors", cursor_count);
772 }
773 }
774
775 pub fn remove_cursor(&self, name: &str) {
776 let mut guard = self.mutable_session_data.write().unwrap();
777 guard.cursors.remove(name);
778 }
779
780 pub fn get_cursor(&self, name: &str) -> Option<Arc<RecordBatchStreamCursor>> {
781 let guard = self.mutable_session_data.read().unwrap();
782 let rb = guard.cursors.get(name);
783 rb.cloned()
784 }
785
786 pub fn snapshots(&self) -> HashMap<u64, u64> {
787 self.snapshot_seqs.read().unwrap().clone()
788 }
789
790 pub fn sst_min_sequences(&self) -> HashMap<u64, u64> {
791 self.sst_min_sequences.read().unwrap().clone()
792 }
793
794 pub fn get_snapshot(&self, region_id: u64) -> Option<u64> {
795 self.snapshot_seqs.read().unwrap().get(®ion_id).cloned()
796 }
797
798 pub fn set_snapshot(&self, region_id: u64, sequence: u64) {
799 self.snapshot_seqs
800 .write()
801 .unwrap()
802 .insert(region_id, sequence);
803 }
804
805 pub fn auto_string_to_numeric(&self) -> bool {
807 matches!(self.channel, Channel::Mysql)
808 }
809
810 pub fn sst_min_sequence(&self, region_id: u64) -> Option<u64> {
812 self.sst_min_sequences
813 .read()
814 .unwrap()
815 .get(®ion_id)
816 .copied()
817 }
818
819 pub fn process_id(&self) -> u32 {
820 self.process_id
821 }
822
823 pub fn conn_info(&self) -> &ConnInfo {
825 &self.conn_info
826 }
827
828 pub fn protocol_ctx(&self) -> &ProtocolCtx {
829 &self.protocol_ctx
830 }
831
832 pub fn set_protocol_ctx(&mut self, protocol_ctx: ProtocolCtx) {
833 self.protocol_ctx = protocol_ctx;
834 }
835}
836
837impl QueryContextBuilder {
838 pub fn build(self) -> QueryContext {
839 let channel = self.channel.unwrap_or_default();
840 let mut extensions = self.extensions.unwrap_or_default();
841 extensions
842 .entry(REMOTE_QUERY_ID_EXTENSION_KEY.to_string())
843 .or_insert_with(generate_remote_query_id);
844 QueryContext {
845 current_catalog: self
846 .current_catalog
847 .unwrap_or_else(|| DEFAULT_CATALOG_NAME.to_string()),
848 snapshot_seqs: self.snapshot_seqs.unwrap_or_default(),
849 sst_min_sequences: self.sst_min_sequences.unwrap_or_default(),
850 mutable_session_data: self.mutable_session_data.unwrap_or_default(),
851 mutable_query_context_data: self.mutable_query_context_data.unwrap_or_default(),
852 sql_dialect: self
853 .sql_dialect
854 .unwrap_or_else(|| Arc::new(GreptimeDbDialect {})),
855 extensions,
856 query_options_snapshotted: false,
857 configuration_parameter: self
858 .configuration_parameter
859 .unwrap_or_else(|| Arc::new(ConfigurationVariables::default())),
860 channel,
861 batching_enabled: self.batching_enabled.unwrap_or_default(),
862 admitted_write: None,
863 metric_discovery_scope: MetricDiscoveryScope::default(),
864 write_progress: None,
865 body_memory_bytes: Weak::new(),
866 confirmed_writes: false,
867 logical_batching_enabled: self.logical_batching_enabled.unwrap_or_default(),
868 process_id: self.process_id.unwrap_or_default(),
869 conn_info: self.conn_info.unwrap_or_default(),
870 protocol_ctx: self.protocol_ctx.unwrap_or_default(),
871 }
872 }
873
874 pub fn set_extension(mut self, key: String, value: String) -> Self {
875 self.extensions
876 .get_or_insert_with(HashMap::new)
877 .insert(key, value);
878 self
879 }
880}
881
882#[derive(Debug, Clone, Default)]
883pub struct ConnInfo {
884 pub client_addr: Option<SocketAddr>,
885 pub channel: Channel,
886}
887
888impl Display for ConnInfo {
889 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
890 write!(
891 f,
892 "{}[{}]",
893 self.channel,
894 self.client_addr
895 .map(|addr| addr.to_string())
896 .as_deref()
897 .unwrap_or("unknown client addr")
898 )
899 }
900}
901
902impl ConnInfo {
903 pub fn new(client_addr: Option<SocketAddr>, channel: Channel) -> Self {
904 Self {
905 client_addr,
906 channel,
907 }
908 }
909}
910
911pub fn dialect_for_channel(channel: Channel) -> Arc<dyn Dialect + Send + Sync> {
913 match channel {
914 Channel::Mysql => Arc::new(MySqlDialect {}),
915 Channel::Postgres => Arc::new(PostgreSqlDialect {}),
916 _ => Arc::new(GenericDialect {}),
917 }
918}
919
920#[derive(Default, Debug)]
921pub struct ConfigurationVariables {
922 postgres_bytea_output: ArcSwap<PGByteaOutputValue>,
923 pg_datestyle_format: ArcSwap<(PGDateTimeStyle, PGDateOrder)>,
924 pg_intervalstyle_format: ArcSwap<PGIntervalStyle>,
925 query_options: RwLock<HashMap<String, String>>,
926}
927
928impl Clone for ConfigurationVariables {
929 fn clone(&self) -> Self {
930 Self {
931 postgres_bytea_output: ArcSwap::new(self.postgres_bytea_output.load().clone()),
932 pg_datestyle_format: ArcSwap::new(self.pg_datestyle_format.load().clone()),
933 pg_intervalstyle_format: ArcSwap::new(self.pg_intervalstyle_format.load().clone()),
934 query_options: RwLock::new(self.query_options.read().unwrap().clone()),
935 }
936 }
937}
938
939impl ConfigurationVariables {
940 pub fn new() -> Self {
941 Self::default()
942 }
943
944 pub fn set_postgres_bytea_output(&self, value: PGByteaOutputValue) {
945 let _ = self.postgres_bytea_output.swap(Arc::new(value));
946 }
947
948 pub fn postgres_bytea_output(&self) -> Arc<PGByteaOutputValue> {
949 self.postgres_bytea_output.load().clone()
950 }
951
952 pub fn pg_datetime_style(&self) -> Arc<(PGDateTimeStyle, PGDateOrder)> {
953 self.pg_datestyle_format.load().clone()
954 }
955
956 pub fn set_pg_datetime_style(&self, style: PGDateTimeStyle, order: PGDateOrder) {
957 self.pg_datestyle_format.swap(Arc::new((style, order)));
958 }
959
960 pub fn pg_intervalstyle_format(&self) -> Arc<PGIntervalStyle> {
961 self.pg_intervalstyle_format.load().clone()
962 }
963
964 pub fn set_pg_intervalstyle_format(&self, value: PGIntervalStyle) {
965 self.pg_intervalstyle_format.swap(Arc::new(value));
966 }
967
968 pub fn allow_query_fallback(&self) -> bool {
969 self.query_options().get("query.allow_query_fallback") == Some(&"true".to_string())
970 }
971
972 pub fn set_allow_query_fallback(&self, allow: bool) {
973 self.query_options
974 .write()
975 .unwrap()
976 .insert("query.allow_query_fallback".to_string(), allow.to_string());
977 }
978
979 pub fn set_query_option(
981 &self,
982 key: &str,
983 value: &str,
984 ) -> Result<(), crate::session_config::Error> {
985 let (canonical, normalized) = crate::query_options::parse_query_option(
986 key,
987 value,
988 crate::query_options::MAX_PUBLIC_PARALLELISM,
989 )?
990 .ok_or_else(|| crate::session_config::Error::InvalidConfigValue {
991 name: key.to_string(),
992 value: value.to_string(),
993 hint: "Not a supported query option".to_string(),
994 location: snafu::Location::new(file!(), line!(), column!()),
995 })?;
996 self.query_options
997 .write()
998 .unwrap()
999 .insert(canonical, normalized);
1000 Ok(())
1001 }
1002
1003 pub fn query_options(&self) -> HashMap<String, String> {
1005 self.query_options.read().unwrap().clone()
1006 }
1007}
1008
1009#[cfg(test)]
1010mod test {
1011 use std::collections::HashMap;
1012
1013 use common_catalog::consts::DEFAULT_CATALOG_NAME;
1014
1015 use crate::Session;
1016 use crate::context::{Channel, *};
1017
1018 #[test]
1019 fn test_query_parallelism_wire_accepts_legacy_value() {
1020 let mut context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
1021 context.set_extension("query_parallelism", "2048");
1022
1023 assert_eq!(
1024 context
1025 .effective_query_options()
1026 .unwrap()
1027 .get("query.parallelism"),
1028 Some(&"2048".to_string())
1029 );
1030 }
1031
1032 #[test]
1033 fn test_set_query_parallelism_public_limit() {
1034 let context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
1035 assert!(
1036 context
1037 .configuration_parameter()
1038 .set_query_option("query.parallelism", "1025")
1039 .is_err()
1040 );
1041 assert!(
1042 context
1043 .configuration_parameter()
1044 .set_query_option("query.parallelism", "1024")
1045 .is_ok()
1046 );
1047 }
1048
1049 #[test]
1050 fn test_session() {
1051 let session = Session::new(
1052 Some("127.0.0.1:9000".parse().unwrap()),
1053 Channel::Mysql,
1054 Default::default(),
1055 100,
1056 );
1057 assert_eq!(session.user_info().username(), "greptime");
1059
1060 assert_eq!(session.conn_info().channel, Channel::Mysql);
1062 let client_addr = session.conn_info().client_addr.as_ref().unwrap();
1063 assert_eq!(client_addr.ip().to_string(), "127.0.0.1");
1064 assert_eq!(client_addr.port(), 9000);
1065
1066 assert_eq!("mysql[127.0.0.1:9000]", session.conn_info().to_string());
1067 assert_eq!(100, session.process_id());
1068
1069 let query_ctx = session.new_query_context();
1070 assert!(query_ctx.remote_query_id().is_some());
1071 }
1072
1073 #[test]
1074 fn test_context_db_string() {
1075 let context = QueryContext::with("a0b1c2d3", "test");
1076 assert_eq!("a0b1c2d3-test", context.get_db_string());
1077
1078 let context = QueryContext::with(DEFAULT_CATALOG_NAME, "test");
1079 assert_eq!("test", context.get_db_string());
1080 }
1081
1082 #[test]
1083 fn test_fork_has_independent_mutable_session_data() {
1084 let context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
1085 let fork = context.fork();
1086
1087 fork.set_current_schema("private");
1088
1089 assert_eq!(context.current_schema(), "public");
1090 assert_eq!(fork.current_schema(), "private");
1091 }
1092
1093 #[test]
1094 fn test_skip_wal_default_builder_and_fork() {
1095 let default_context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
1096 assert!(!default_context.skip_wal());
1097 assert!(!QueryContextBuilder::default().build().skip_wal());
1098 let context = QueryContextBuilder::default().skip_wal(true).build();
1099 assert!(context.skip_wal());
1100 let fork = context.fork();
1101 assert!(fork.skip_wal());
1102 fork.set_skip_wal(false);
1103 assert!(context.skip_wal());
1104 assert!(!fork.skip_wal());
1105 context.set_skip_wal(false);
1106 fork.set_skip_wal(true);
1107 assert!(!context.skip_wal());
1108 assert!(fork.skip_wal());
1109 }
1110
1111 #[test]
1112 fn test_write_admission_is_local_and_database_scoped() {
1113 let ctx = QueryContext::with_channel("greptime", "public", Channel::Otlp);
1114 let admitted = ctx.with_write_admission();
1115 assert_eq!(ctx.write_rows_to_admit("greptime", "public", 100), 100);
1116 assert_eq!(admitted.write_rows_to_admit("greptime", "public", 100), 0);
1117 assert_eq!(admitted.write_rows_to_admit("greptime", "other", 100), 100);
1118 assert_eq!(admitted.write_rows_to_admit("other", "public", 100), 100);
1119 assert_eq!(admitted.channel(), Channel::Otlp);
1120 assert_eq!(
1121 admitted
1122 .fork()
1123 .write_rows_to_admit("greptime", "public", 100),
1124 0
1125 );
1126 let wire: api::v1::QueryContext = admitted.into();
1127 let restored = QueryContext::try_from(wire).unwrap();
1128 assert_eq!(restored.write_rows_to_admit("greptime", "public", 100), 100);
1129 }
1130
1131 #[test]
1132 fn test_skip_wal_is_not_serialized_in_query_context() {
1133 let context = QueryContextBuilder::default().skip_wal(true).build();
1134 let api_context: api::v1::QueryContext = context.into();
1135 assert!(
1136 !api_context
1137 .extensions
1138 .contains_key(crate::hints::INSERT_SKIP_WAL_HINT)
1139 );
1140 let restored: QueryContext = api_context.try_into().unwrap();
1141 assert!(!restored.skip_wal());
1142 }
1143
1144 #[test]
1145 fn test_api_query_context_roundtrip_with_sequences() {
1146 let api_ctx = api::v1::QueryContext {
1147 current_catalog: "c1".to_string(),
1148 current_schema: "s1".to_string(),
1149 timezone: "UTC".to_string(),
1150 extensions: HashMap::from([("flow.return_region_seq".to_string(), "true".to_string())]),
1151 channel: Channel::Internal as u32,
1152 snapshot_seqs: Some(api::v1::SnapshotSequences {
1153 snapshot_seqs: HashMap::from([(1, 100)]),
1154 sst_min_sequences: HashMap::from([(1, 90)]),
1155 }),
1156 explain: None,
1157 };
1158
1159 let session_ctx: QueryContext = api_ctx.clone().try_into().unwrap();
1160 let roundtrip_api: api::v1::QueryContext = session_ctx.into();
1161
1162 assert_eq!(roundtrip_api.current_catalog, api_ctx.current_catalog);
1163 assert_eq!(roundtrip_api.current_schema, api_ctx.current_schema);
1164 assert_eq!(roundtrip_api.timezone, api_ctx.timezone);
1165 assert_eq!(
1166 roundtrip_api.extensions.get("flow.return_region_seq"),
1167 Some(&"true".to_string())
1168 );
1169 assert!(
1170 roundtrip_api
1171 .extensions
1172 .contains_key(REMOTE_QUERY_ID_EXTENSION_KEY)
1173 );
1174 assert_eq!(roundtrip_api.channel, api_ctx.channel);
1175 assert_eq!(roundtrip_api.snapshot_seqs, api_ctx.snapshot_seqs);
1176 }
1177
1178 #[test]
1179 fn test_query_context_remote_query_id_round_trip() {
1180 let query_id = "0195f4fd-c503-7c54-8b8f-7dfb8f6f9c4a";
1181 let ctx = QueryContextBuilder::default()
1182 .current_catalog(DEFAULT_CATALOG_NAME.to_string())
1183 .current_schema("public".to_string())
1184 .set_extension(
1185 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
1186 query_id.to_string(),
1187 )
1188 .build();
1189
1190 assert_eq!(ctx.remote_query_id(), Some(query_id));
1191 assert_eq!(ctx.remote_query_id_value().unwrap().to_string(), query_id);
1192
1193 let proto: api::v1::QueryContext = (&ctx).into();
1194 let restored = QueryContext::try_from(proto).unwrap();
1195 assert_eq!(restored.remote_query_id(), Some(query_id));
1196 assert_eq!(
1197 restored.remote_query_id_value().unwrap().to_string(),
1198 query_id
1199 );
1200 }
1201
1202 #[test]
1203 fn test_query_context_read_preference_wire_values() {
1204 let wire = |value: Option<&str>| api::v1::QueryContext {
1205 current_catalog: DEFAULT_CATALOG_NAME.to_string(),
1206 current_schema: DEFAULT_SCHEMA_NAME.to_string(),
1207 timezone: "UTC".to_string(),
1208 extensions: value
1209 .map(|value| {
1210 HashMap::from([(READ_PREFERENCE_EXTENSION_KEY.to_string(), value.to_string())])
1211 })
1212 .unwrap_or_default(),
1213 channel: Channel::Internal as u32,
1214 snapshot_seqs: None,
1215 explain: None,
1216 };
1217
1218 let header = RegionRequestHeader::default();
1219 let header_context = QueryContext::try_from(&header).unwrap();
1220 assert_eq!(header_context.read_preference(), ReadPreference::Leader);
1221
1222 for value in [None, Some("leader"), Some("LEADER")] {
1223 let ctx = QueryContext::try_from(wire(value)).unwrap();
1224 assert_eq!(ctx.read_preference(), ReadPreference::Leader);
1225 assert!(!ctx.extensions().contains_key(READ_PREFERENCE_EXTENSION_KEY));
1226 }
1227 for value in ["", "unknown"] {
1228 let error = QueryContext::try_from(wire(Some(value))).unwrap_err();
1229 assert!(matches!(
1230 error,
1231 crate::session_config::Error::InvalidConfigValue {
1232 name,
1233 value: actual,
1234 ..
1235 } if name == "read_preference" && actual == value
1236 ));
1237 }
1238 }
1239
1240 #[test]
1241 fn test_legacy_query_context_wire_defaults_to_leader() {
1242 use prost::Message;
1243
1244 let legacy = api::v1::QueryContext::decode(
1245 include_bytes!(
1246 "../../../tests/compatibility/wire/read_preference/legacy_query_context.pb"
1247 )
1248 .as_slice(),
1249 )
1250 .unwrap();
1251 assert_eq!(legacy.current_catalog, "c1");
1252 assert_eq!(legacy.current_schema, "s1");
1253 assert_eq!(legacy.timezone, "UTC");
1254 assert_eq!(legacy.channel, Channel::Internal as u32);
1255 assert_eq!(
1256 legacy
1257 .extensions
1258 .get("flow.return_region_seq")
1259 .map(String::as_str),
1260 Some("true")
1261 );
1262 assert!(
1263 !legacy
1264 .extensions
1265 .contains_key(READ_PREFERENCE_EXTENSION_KEY)
1266 );
1267
1268 let restored = QueryContext::try_from(legacy).unwrap();
1269 assert_eq!(restored.read_preference(), ReadPreference::Leader);
1270 assert_eq!(restored.current_catalog(), "c1");
1271 assert_eq!(restored.current_schema(), "s1");
1272 assert_eq!(restored.timezone().to_string(), "UTC");
1273 assert_eq!(restored.channel(), Channel::Internal);
1274 assert_eq!(restored.extension("flow.return_region_seq"), Some("true"));
1275
1276 let outbound: api::v1::QueryContext = restored.into();
1277 let roundtrip = api::v1::QueryContext::decode(outbound.encode_to_vec().as_slice()).unwrap();
1278 assert_eq!(roundtrip.current_catalog, "c1");
1279 assert_eq!(roundtrip.current_schema, "s1");
1280 assert_eq!(roundtrip.timezone, "UTC");
1281 assert_eq!(roundtrip.channel, Channel::Internal as u32);
1282 assert_eq!(
1283 roundtrip
1284 .extensions
1285 .get("flow.return_region_seq")
1286 .map(String::as_str),
1287 Some("true")
1288 );
1289 assert!(
1290 !roundtrip
1291 .extensions
1292 .contains_key(READ_PREFERENCE_EXTENSION_KEY)
1293 );
1294 }
1295
1296 #[test]
1297 fn test_outbound_read_preference_clears_stale_extension() {
1298 let context = QueryContextBuilder::default()
1299 .set_extension(
1300 READ_PREFERENCE_EXTENSION_KEY.to_string(),
1301 "stale".to_string(),
1302 )
1303 .set_extension("unrelated".to_string(), "preserved".to_string())
1304 .build();
1305 let wire: api::v1::QueryContext = context.into();
1306 assert!(!wire.extensions.contains_key(READ_PREFERENCE_EXTENSION_KEY));
1307 assert_eq!(
1308 wire.extensions.get("unrelated").map(String::as_str),
1309 Some("preserved")
1310 );
1311 }
1312
1313 #[test]
1314 fn test_live_analyze_metrics_requires_matching_remote_query_id() {
1315 let mut ctx = QueryContext::arc().as_ref().clone();
1316 assert!(!ctx.live_analyze_metrics_enabled());
1317
1318 ctx.enable_live_analyze_metrics();
1319 assert!(ctx.live_analyze_metrics_enabled());
1320
1321 ctx.set_extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY, "true");
1322 assert!(!ctx.live_analyze_metrics_enabled());
1323
1324 ctx.set_extension(LIVE_ANALYZE_METRICS_EXTENSION_KEY, "another-query-id");
1325 assert!(!ctx.live_analyze_metrics_enabled());
1326 }
1327 #[test]
1328 fn test_batching_selection_is_local_only() {
1329 let mut ctx = QueryContextBuilder::default().build();
1330 assert!(!ctx.batching_enabled());
1331 assert!(!ctx.logical_batching_enabled());
1332 ctx.set_logical_batching_enabled(true);
1333 assert!(ctx.clone().logical_batching_enabled());
1334 assert!(ctx.fork().logical_batching_enabled());
1335 ctx.set_batching_enabled(true);
1336 assert!(ctx.clone().batching_enabled());
1337 assert!(ctx.fork().batching_enabled());
1338 let wire: api::v1::QueryContext = ctx.into();
1339 let restored = QueryContext::try_from(wire).unwrap();
1340 assert!(!restored.batching_enabled());
1341 assert!(!restored.logical_batching_enabled());
1342 let ctx = QueryContextBuilder::default()
1343 .set_extension("batching_enabled".to_string(), "true".to_string())
1344 .build();
1345 assert!(!ctx.batching_enabled());
1346 }
1347}