1use std::collections::HashMap;
16use std::fmt::{Display, Formatter};
17use std::net::SocketAddr;
18use std::sync::{Arc, RwLock};
19use std::time::Duration;
20
21use api::v1::ExplainOptions;
22use api::v1::region::RegionRequestHeader;
23use arc_swap::ArcSwap;
24use auth::UserInfoRef;
25use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
26use common_catalog::{build_db_string, parse_catalog_and_schema_from_db_string};
27use common_recordbatch::cursor::RecordBatchStreamCursor;
28use common_telemetry::warn;
29use common_time::Timezone;
30use common_time::timezone::parse_timezone;
31use datafusion_common::config::ConfigOptions;
32use derive_builder::Builder;
33use sql::dialect::{Dialect, GenericDialect, GreptimeDbDialect, MySqlDialect, PostgreSqlDialect};
34
35pub use crate::hints::{
36 REMOTE_QUERY_ID_EXTENSION_KEY, SUPPORT_FLIGHT_METRICS_BEFORE_BATCH_EXTENSION_KEY,
37};
38use crate::protocol_ctx::ProtocolCtx;
39use crate::query_id::QueryId;
40use crate::session_config::{PGByteaOutputValue, PGDateOrder, PGDateTimeStyle, PGIntervalStyle};
41use crate::{MutableInner, ReadPreference};
42
43pub type QueryContextRef = Arc<QueryContext>;
44pub type ConnInfoRef = Arc<ConnInfo>;
45
46pub const FLIGHT_METRICS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1);
47
48const CURSOR_COUNT_WARNING_LIMIT: usize = 10;
49
50pub fn generate_remote_query_id() -> String {
51 generate_remote_query_id_value().to_string()
52}
53
54pub fn generate_remote_query_id_value() -> QueryId {
55 QueryId::new()
56}
57
58#[derive(Debug, Builder, Clone)]
59#[builder(pattern = "owned")]
60#[builder(build_fn(skip))]
61pub struct QueryContext {
62 current_catalog: String,
63 snapshot_seqs: Arc<RwLock<HashMap<u64, u64>>>,
67 sst_min_sequences: Arc<RwLock<HashMap<u64, u64>>>,
69 #[builder(default)]
71 mutable_session_data: Arc<RwLock<MutableInner>>,
72 #[builder(default)]
73 mutable_query_context_data: Arc<RwLock<QueryContextMutableFields>>,
74 sql_dialect: Arc<dyn Dialect + Send + Sync>,
75 #[builder(default)]
76 extensions: HashMap<String, String>,
77 #[builder(default)]
79 configuration_parameter: Arc<ConfigurationVariables>,
80 #[builder(default)]
82 channel: Channel,
83 #[builder(default)]
85 process_id: u32,
86 #[builder(default)]
88 conn_info: ConnInfo,
89 #[builder(default)]
91 protocol_ctx: ProtocolCtx,
92}
93
94#[derive(Debug, Builder, Clone, Default)]
96pub struct QueryContextMutableFields {
97 warning: Option<String>,
98 explain_format: Option<String>,
100 explain_options: Option<ExplainOptions>,
102}
103
104impl Display for QueryContext {
105 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
106 write!(
107 f,
108 "QueryContext{{catalog: {}, schema: {}}}",
109 self.current_catalog(),
110 self.current_schema()
111 )
112 }
113}
114
115impl QueryContextBuilder {
116 pub fn current_schema(mut self, schema: String) -> Self {
117 if self.mutable_session_data.is_none() {
118 self.mutable_session_data = Some(Arc::new(RwLock::new(MutableInner::default())));
119 }
120
121 self.mutable_session_data
123 .as_mut()
124 .unwrap()
125 .write()
126 .unwrap()
127 .schema = schema;
128 self
129 }
130
131 pub fn timezone(mut self, timezone: Timezone) -> Self {
132 if self.mutable_session_data.is_none() {
133 self.mutable_session_data = Some(Arc::new(RwLock::new(MutableInner::default())));
134 }
135
136 self.mutable_session_data
137 .as_mut()
138 .unwrap()
139 .write()
140 .unwrap()
141 .timezone = timezone;
142 self
143 }
144
145 pub fn explain_options(mut self, explain_options: Option<ExplainOptions>) -> Self {
146 self.mutable_query_context_data
147 .get_or_insert_default()
148 .write()
149 .unwrap()
150 .explain_options = explain_options;
151 self
152 }
153
154 pub fn read_preference(mut self, read_preference: ReadPreference) -> Self {
155 self.mutable_session_data
156 .get_or_insert_default()
157 .write()
158 .unwrap()
159 .read_preference = read_preference;
160 self
161 }
162}
163
164impl From<&RegionRequestHeader> for QueryContext {
165 fn from(value: &RegionRequestHeader) -> Self {
166 if let Some(ctx) = &value.query_context {
167 ctx.clone().into()
168 } else {
169 QueryContextBuilder::default()
170 .set_extension(
171 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
172 generate_remote_query_id(),
173 )
174 .build()
175 }
176 }
177}
178
179impl From<api::v1::QueryContext> for QueryContext {
180 fn from(ctx: api::v1::QueryContext) -> Self {
181 let sequences = ctx.snapshot_seqs.as_ref();
182 QueryContextBuilder::default()
183 .current_catalog(ctx.current_catalog)
184 .current_schema(ctx.current_schema)
185 .timezone(parse_timezone(Some(&ctx.timezone)))
186 .extensions(ctx.extensions)
187 .channel(ctx.channel.into())
188 .snapshot_seqs(Arc::new(RwLock::new(
189 sequences
190 .map(|x| x.snapshot_seqs.clone())
191 .unwrap_or_default(),
192 )))
193 .sst_min_sequences(Arc::new(RwLock::new(
194 sequences
195 .map(|x| x.sst_min_sequences.clone())
196 .unwrap_or_default(),
197 )))
198 .explain_options(ctx.explain)
199 .build()
200 }
201}
202
203impl From<QueryContext> for api::v1::QueryContext {
204 fn from(
205 QueryContext {
206 current_catalog,
207 mutable_session_data: mutable_inner,
208 extensions,
209 channel,
210 snapshot_seqs,
211 sst_min_sequences,
212 mutable_query_context_data,
213 ..
214 }: QueryContext,
215 ) -> Self {
216 let explain = mutable_query_context_data.read().unwrap().explain_options;
217 let mutable_inner = mutable_inner.read().unwrap();
218 api::v1::QueryContext {
219 current_catalog,
220 current_schema: mutable_inner.schema.clone(),
221 timezone: mutable_inner.timezone.to_string(),
222 extensions,
223 channel: channel as u32,
224 snapshot_seqs: Some(api::v1::SnapshotSequences {
225 snapshot_seqs: snapshot_seqs.read().unwrap().clone(),
226 sst_min_sequences: sst_min_sequences.read().unwrap().clone(),
227 }),
228 explain,
229 }
230 }
231}
232
233impl From<&QueryContext> for api::v1::QueryContext {
234 fn from(ctx: &QueryContext) -> Self {
235 ctx.clone().into()
236 }
237}
238
239impl QueryContext {
240 pub fn fork(&self) -> Self {
245 let mut fork = self.clone();
246 fork.mutable_session_data = Arc::new(RwLock::new(
247 self.mutable_session_data.read().unwrap().clone(),
248 ));
249 fork
250 }
251
252 pub fn arc() -> QueryContextRef {
253 Arc::new(
254 QueryContextBuilder::default()
255 .set_extension(
256 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
257 generate_remote_query_id(),
258 )
259 .build(),
260 )
261 }
262
263 pub fn create_config_options(&self) -> ConfigOptions {
265 let mut config = ConfigOptions::default();
266 config.execution.time_zone = Some(self.timezone().to_string());
267 config
268 }
269
270 pub fn with(catalog: &str, schema: &str) -> QueryContext {
271 QueryContextBuilder::default()
272 .current_catalog(catalog.to_string())
273 .current_schema(schema.to_string())
274 .set_extension(
275 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
276 generate_remote_query_id(),
277 )
278 .build()
279 }
280
281 pub fn with_channel(catalog: &str, schema: &str, channel: Channel) -> QueryContext {
282 QueryContextBuilder::default()
283 .current_catalog(catalog.to_string())
284 .current_schema(schema.to_string())
285 .channel(channel)
286 .set_extension(
287 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
288 generate_remote_query_id(),
289 )
290 .build()
291 }
292
293 pub fn with_db_name(db_name: Option<&str>) -> QueryContext {
294 let (catalog, schema) = db_name
295 .map(|db| {
296 let (catalog, schema) = parse_catalog_and_schema_from_db_string(db);
297 (catalog, schema)
298 })
299 .unwrap_or_else(|| {
300 (
301 DEFAULT_CATALOG_NAME.to_string(),
302 DEFAULT_SCHEMA_NAME.to_string(),
303 )
304 });
305 QueryContextBuilder::default()
306 .current_catalog(catalog)
307 .current_schema(schema.clone())
308 .set_extension(
309 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
310 generate_remote_query_id(),
311 )
312 .build()
313 }
314
315 pub fn current_schema(&self) -> String {
316 self.mutable_session_data.read().unwrap().schema.clone()
317 }
318
319 pub fn set_current_schema(&self, new_schema: &str) {
320 self.mutable_session_data.write().unwrap().schema = new_schema.to_string();
321 }
322
323 pub fn current_catalog(&self) -> &str {
324 &self.current_catalog
325 }
326
327 pub fn set_current_catalog(&mut self, new_catalog: &str) {
328 self.current_catalog = new_catalog.to_string();
329 }
330
331 pub fn sql_dialect(&self) -> &(dyn Dialect + Send + Sync) {
332 &*self.sql_dialect
333 }
334
335 pub fn get_db_string(&self) -> String {
336 let catalog = self.current_catalog();
337 let schema = self.current_schema();
338 build_db_string(catalog, &schema)
339 }
340
341 pub fn timezone(&self) -> Timezone {
342 self.mutable_session_data.read().unwrap().timezone.clone()
343 }
344
345 pub fn set_timezone(&self, timezone: Timezone) {
346 self.mutable_session_data.write().unwrap().timezone = timezone;
347 }
348
349 pub fn read_preference(&self) -> ReadPreference {
350 self.mutable_session_data.read().unwrap().read_preference
351 }
352
353 pub fn set_read_preference(&self, read_preference: ReadPreference) {
354 self.mutable_session_data.write().unwrap().read_preference = read_preference;
355 }
356
357 pub fn current_user(&self) -> UserInfoRef {
358 self.mutable_session_data.read().unwrap().user_info.clone()
359 }
360
361 pub fn set_current_user(&self, user: UserInfoRef) {
362 self.mutable_session_data.write().unwrap().user_info = user;
363 }
364
365 pub fn set_extension<S1: Into<String>, S2: Into<String>>(&mut self, key: S1, value: S2) {
366 self.extensions.insert(key.into(), value.into());
367 }
368
369 pub fn extension<S: AsRef<str>>(&self, key: S) -> Option<&str> {
370 self.extensions.get(key.as_ref()).map(|v| v.as_str())
371 }
372
373 pub fn remote_query_id(&self) -> Option<&str> {
374 self.extension(REMOTE_QUERY_ID_EXTENSION_KEY)
375 }
376
377 pub fn remote_query_id_value(&self) -> Option<QueryId> {
378 self.remote_query_id()
379 .and_then(|query_id| query_id.parse().ok())
380 }
381
382 pub fn extensions(&self) -> HashMap<String, String> {
383 self.extensions.clone()
384 }
385
386 pub fn quote_style(&self) -> char {
388 if self.sql_dialect().is_delimited_identifier_start('"') {
389 '"'
390 } else if self.sql_dialect().is_delimited_identifier_start('\'') {
391 '\''
392 } else {
393 '`'
394 }
395 }
396
397 pub fn configuration_parameter(&self) -> &ConfigurationVariables {
398 &self.configuration_parameter
399 }
400
401 pub fn channel(&self) -> Channel {
402 self.channel
403 }
404
405 pub fn set_channel(&mut self, channel: Channel) {
406 self.channel = channel;
407 }
408
409 pub fn warning(&self) -> Option<String> {
410 self.mutable_query_context_data
411 .read()
412 .unwrap()
413 .warning
414 .clone()
415 }
416
417 pub fn set_warning(&self, msg: String) {
418 self.mutable_query_context_data.write().unwrap().warning = Some(msg);
419 }
420
421 pub fn explain_format(&self) -> Option<String> {
422 self.mutable_query_context_data
423 .read()
424 .unwrap()
425 .explain_format
426 .clone()
427 }
428
429 pub fn set_explain_format(&self, format: String) {
430 self.mutable_query_context_data
431 .write()
432 .unwrap()
433 .explain_format = Some(format);
434 }
435
436 pub fn explain_verbose(&self) -> bool {
437 self.mutable_query_context_data
438 .read()
439 .unwrap()
440 .explain_options
441 .map(|opts| opts.verbose)
442 .unwrap_or(false)
443 }
444
445 pub fn set_explain_verbose(&self, verbose: bool) {
446 self.mutable_query_context_data
447 .write()
448 .unwrap()
449 .explain_options
450 .get_or_insert_default()
451 .verbose = verbose;
452 }
453
454 pub fn query_timeout(&self) -> Option<Duration> {
455 self.mutable_session_data.read().unwrap().query_timeout
456 }
457
458 pub fn query_timeout_as_millis(&self) -> u128 {
459 let timeout = self.mutable_session_data.read().unwrap().query_timeout;
460 if let Some(t) = timeout {
461 return t.as_millis();
462 }
463 0
464 }
465
466 pub fn set_query_timeout(&self, timeout: Duration) {
467 self.mutable_session_data.write().unwrap().query_timeout = Some(timeout);
468 }
469
470 pub fn insert_cursor(&self, name: String, rb: RecordBatchStreamCursor) {
471 let mut guard = self.mutable_session_data.write().unwrap();
472 guard.cursors.insert(name, Arc::new(rb));
473
474 let cursor_count = guard.cursors.len();
475 if cursor_count > CURSOR_COUNT_WARNING_LIMIT {
476 warn!("Current connection has {} open cursors", cursor_count);
477 }
478 }
479
480 pub fn remove_cursor(&self, name: &str) {
481 let mut guard = self.mutable_session_data.write().unwrap();
482 guard.cursors.remove(name);
483 }
484
485 pub fn get_cursor(&self, name: &str) -> Option<Arc<RecordBatchStreamCursor>> {
486 let guard = self.mutable_session_data.read().unwrap();
487 let rb = guard.cursors.get(name);
488 rb.cloned()
489 }
490
491 pub fn snapshots(&self) -> HashMap<u64, u64> {
492 self.snapshot_seqs.read().unwrap().clone()
493 }
494
495 pub fn sst_min_sequences(&self) -> HashMap<u64, u64> {
496 self.sst_min_sequences.read().unwrap().clone()
497 }
498
499 pub fn get_snapshot(&self, region_id: u64) -> Option<u64> {
500 self.snapshot_seqs.read().unwrap().get(®ion_id).cloned()
501 }
502
503 pub fn set_snapshot(&self, region_id: u64, sequence: u64) {
504 self.snapshot_seqs
505 .write()
506 .unwrap()
507 .insert(region_id, sequence);
508 }
509
510 pub fn auto_string_to_numeric(&self) -> bool {
512 matches!(self.channel, Channel::Mysql)
513 }
514
515 pub fn sst_min_sequence(&self, region_id: u64) -> Option<u64> {
517 self.sst_min_sequences
518 .read()
519 .unwrap()
520 .get(®ion_id)
521 .copied()
522 }
523
524 pub fn process_id(&self) -> u32 {
525 self.process_id
526 }
527
528 pub fn conn_info(&self) -> &ConnInfo {
530 &self.conn_info
531 }
532
533 pub fn protocol_ctx(&self) -> &ProtocolCtx {
534 &self.protocol_ctx
535 }
536
537 pub fn set_protocol_ctx(&mut self, protocol_ctx: ProtocolCtx) {
538 self.protocol_ctx = protocol_ctx;
539 }
540}
541
542impl QueryContextBuilder {
543 pub fn build(self) -> QueryContext {
544 let channel = self.channel.unwrap_or_default();
545 let mut extensions = self.extensions.unwrap_or_default();
546 extensions
547 .entry(REMOTE_QUERY_ID_EXTENSION_KEY.to_string())
548 .or_insert_with(generate_remote_query_id);
549 QueryContext {
550 current_catalog: self
551 .current_catalog
552 .unwrap_or_else(|| DEFAULT_CATALOG_NAME.to_string()),
553 snapshot_seqs: self.snapshot_seqs.unwrap_or_default(),
554 sst_min_sequences: self.sst_min_sequences.unwrap_or_default(),
555 mutable_session_data: self.mutable_session_data.unwrap_or_default(),
556 mutable_query_context_data: self.mutable_query_context_data.unwrap_or_default(),
557 sql_dialect: self
558 .sql_dialect
559 .unwrap_or_else(|| Arc::new(GreptimeDbDialect {})),
560 extensions,
561 configuration_parameter: self
562 .configuration_parameter
563 .unwrap_or_else(|| Arc::new(ConfigurationVariables::default())),
564 channel,
565 process_id: self.process_id.unwrap_or_default(),
566 conn_info: self.conn_info.unwrap_or_default(),
567 protocol_ctx: self.protocol_ctx.unwrap_or_default(),
568 }
569 }
570
571 pub fn set_extension(mut self, key: String, value: String) -> Self {
572 self.extensions
573 .get_or_insert_with(HashMap::new)
574 .insert(key, value);
575 self
576 }
577}
578
579#[derive(Debug, Clone, Default)]
580pub struct ConnInfo {
581 pub client_addr: Option<SocketAddr>,
582 pub channel: Channel,
583}
584
585impl Display for ConnInfo {
586 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
587 write!(
588 f,
589 "{}[{}]",
590 self.channel,
591 self.client_addr
592 .map(|addr| addr.to_string())
593 .as_deref()
594 .unwrap_or("unknown client addr")
595 )
596 }
597}
598
599impl ConnInfo {
600 pub fn new(client_addr: Option<SocketAddr>, channel: Channel) -> Self {
601 Self {
602 client_addr,
603 channel,
604 }
605 }
606}
607
608#[derive(Debug, PartialEq, Default, Clone, Copy)]
609#[repr(u8)]
610pub enum Channel {
611 #[default]
612 Unknown = 0,
613
614 Mysql = 1,
615 Postgres = 2,
616 HttpSql = 3,
617 Prometheus = 4,
618 Otlp = 5,
619 Grpc = 6,
620 Influx = 7,
621 Opentsdb = 8,
622 Loki = 9,
623 Elasticsearch = 10,
624 Jaeger = 11,
625 Log = 12,
626 Promql = 13,
627 Splunk = 14,
628}
629
630impl From<u32> for Channel {
631 fn from(value: u32) -> Self {
632 match value {
633 1 => Self::Mysql,
634 2 => Self::Postgres,
635 3 => Self::HttpSql,
636 4 => Self::Prometheus,
637 5 => Self::Otlp,
638 6 => Self::Grpc,
639 7 => Self::Influx,
640 8 => Self::Opentsdb,
641 9 => Self::Loki,
642 10 => Self::Elasticsearch,
643 11 => Self::Jaeger,
644 12 => Self::Log,
645 13 => Self::Promql,
646 14 => Self::Splunk,
647 _ => Self::Unknown,
648 }
649 }
650}
651
652impl Channel {
653 pub fn dialect(&self) -> Arc<dyn Dialect + Send + Sync> {
654 match self {
655 Channel::Mysql => Arc::new(MySqlDialect {}),
656 Channel::Postgres => Arc::new(PostgreSqlDialect {}),
657 _ => Arc::new(GenericDialect {}),
658 }
659 }
660}
661
662impl Display for Channel {
663 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
664 write!(f, "{}", self.as_ref())
665 }
666}
667
668impl AsRef<str> for Channel {
669 fn as_ref(&self) -> &str {
670 match self {
671 Channel::Mysql => "mysql",
672 Channel::Postgres => "postgres",
673 Channel::HttpSql => "httpsql",
674 Channel::Prometheus => "prometheus",
675 Channel::Otlp => "otlp",
676 Channel::Grpc => "grpc",
677 Channel::Influx => "influx",
678 Channel::Opentsdb => "opentsdb",
679 Channel::Loki => "loki",
680 Channel::Elasticsearch => "elasticsearch",
681 Channel::Jaeger => "jaeger",
682 Channel::Log => "log",
683 Channel::Promql => "promql",
684 Channel::Splunk => "splunk",
685 Channel::Unknown => "unknown",
686 }
687 }
688}
689
690#[derive(Default, Debug)]
691pub struct ConfigurationVariables {
692 postgres_bytea_output: ArcSwap<PGByteaOutputValue>,
693 pg_datestyle_format: ArcSwap<(PGDateTimeStyle, PGDateOrder)>,
694 pg_intervalstyle_format: ArcSwap<PGIntervalStyle>,
695 allow_query_fallback: ArcSwap<bool>,
696}
697
698impl Clone for ConfigurationVariables {
699 fn clone(&self) -> Self {
700 Self {
701 postgres_bytea_output: ArcSwap::new(self.postgres_bytea_output.load().clone()),
702 pg_datestyle_format: ArcSwap::new(self.pg_datestyle_format.load().clone()),
703 pg_intervalstyle_format: ArcSwap::new(self.pg_intervalstyle_format.load().clone()),
704 allow_query_fallback: ArcSwap::new(self.allow_query_fallback.load().clone()),
705 }
706 }
707}
708
709impl ConfigurationVariables {
710 pub fn new() -> Self {
711 Self::default()
712 }
713
714 pub fn set_postgres_bytea_output(&self, value: PGByteaOutputValue) {
715 let _ = self.postgres_bytea_output.swap(Arc::new(value));
716 }
717
718 pub fn postgres_bytea_output(&self) -> Arc<PGByteaOutputValue> {
719 self.postgres_bytea_output.load().clone()
720 }
721
722 pub fn pg_datetime_style(&self) -> Arc<(PGDateTimeStyle, PGDateOrder)> {
723 self.pg_datestyle_format.load().clone()
724 }
725
726 pub fn set_pg_datetime_style(&self, style: PGDateTimeStyle, order: PGDateOrder) {
727 self.pg_datestyle_format.swap(Arc::new((style, order)));
728 }
729
730 pub fn pg_intervalstyle_format(&self) -> Arc<PGIntervalStyle> {
731 self.pg_intervalstyle_format.load().clone()
732 }
733
734 pub fn set_pg_intervalstyle_format(&self, value: PGIntervalStyle) {
735 self.pg_intervalstyle_format.swap(Arc::new(value));
736 }
737
738 pub fn allow_query_fallback(&self) -> bool {
739 **self.allow_query_fallback.load()
740 }
741
742 pub fn set_allow_query_fallback(&self, allow: bool) {
743 self.allow_query_fallback.swap(Arc::new(allow));
744 }
745}
746
747#[cfg(test)]
748mod test {
749 use std::collections::HashMap;
750
751 use common_catalog::consts::DEFAULT_CATALOG_NAME;
752
753 use super::*;
754 use crate::Session;
755 use crate::context::Channel;
756
757 #[test]
758 fn test_session() {
759 let session = Session::new(
760 Some("127.0.0.1:9000".parse().unwrap()),
761 Channel::Mysql,
762 Default::default(),
763 100,
764 );
765 assert_eq!(session.user_info().username(), "greptime");
767
768 assert_eq!(session.conn_info().channel, Channel::Mysql);
770 let client_addr = session.conn_info().client_addr.as_ref().unwrap();
771 assert_eq!(client_addr.ip().to_string(), "127.0.0.1");
772 assert_eq!(client_addr.port(), 9000);
773
774 assert_eq!("mysql[127.0.0.1:9000]", session.conn_info().to_string());
775 assert_eq!(100, session.process_id());
776
777 let query_ctx = session.new_query_context();
778 assert!(query_ctx.remote_query_id().is_some());
779 }
780
781 #[test]
782 fn test_context_db_string() {
783 let context = QueryContext::with("a0b1c2d3", "test");
784 assert_eq!("a0b1c2d3-test", context.get_db_string());
785
786 let context = QueryContext::with(DEFAULT_CATALOG_NAME, "test");
787 assert_eq!("test", context.get_db_string());
788 }
789
790 #[test]
791 fn test_fork_has_independent_mutable_session_data() {
792 let context = QueryContext::with(DEFAULT_CATALOG_NAME, "public");
793 let fork = context.fork();
794
795 fork.set_current_schema("private");
796
797 assert_eq!(context.current_schema(), "public");
798 assert_eq!(fork.current_schema(), "private");
799 }
800
801 #[test]
802 fn test_api_query_context_roundtrip_with_sequences() {
803 let api_ctx = api::v1::QueryContext {
804 current_catalog: "c1".to_string(),
805 current_schema: "s1".to_string(),
806 timezone: "UTC".to_string(),
807 extensions: HashMap::from([("flow.return_region_seq".to_string(), "true".to_string())]),
808 channel: Channel::Grpc as u32,
809 snapshot_seqs: Some(api::v1::SnapshotSequences {
810 snapshot_seqs: HashMap::from([(1, 100)]),
811 sst_min_sequences: HashMap::from([(1, 90)]),
812 }),
813 explain: None,
814 };
815
816 let session_ctx: QueryContext = api_ctx.clone().into();
817 let roundtrip_api: api::v1::QueryContext = session_ctx.into();
818
819 assert_eq!(roundtrip_api.current_catalog, api_ctx.current_catalog);
820 assert_eq!(roundtrip_api.current_schema, api_ctx.current_schema);
821 assert_eq!(roundtrip_api.timezone, api_ctx.timezone);
822 assert_eq!(
823 roundtrip_api.extensions.get("flow.return_region_seq"),
824 Some(&"true".to_string())
825 );
826 assert!(
827 roundtrip_api
828 .extensions
829 .contains_key(REMOTE_QUERY_ID_EXTENSION_KEY)
830 );
831 assert_eq!(roundtrip_api.channel, api_ctx.channel);
832 assert_eq!(roundtrip_api.snapshot_seqs, api_ctx.snapshot_seqs);
833 }
834
835 #[test]
836 fn test_query_context_remote_query_id_round_trip() {
837 let query_id = "0195f4fd-c503-7c54-8b8f-7dfb8f6f9c4a";
838 let ctx = QueryContextBuilder::default()
839 .current_catalog(DEFAULT_CATALOG_NAME.to_string())
840 .current_schema("public".to_string())
841 .set_extension(
842 REMOTE_QUERY_ID_EXTENSION_KEY.to_string(),
843 query_id.to_string(),
844 )
845 .build();
846
847 assert_eq!(ctx.remote_query_id(), Some(query_id));
848 assert_eq!(ctx.remote_query_id_value().unwrap().to_string(), query_id);
849
850 let proto: api::v1::QueryContext = (&ctx).into();
851 let restored = QueryContext::from(proto);
852 assert_eq!(restored.remote_query_id(), Some(query_id));
853 assert_eq!(
854 restored.remote_query_id_value().unwrap().to_string(),
855 query_id
856 );
857 }
858}