Skip to main content

micromegas/client/
flightsql_client.rs

1use anyhow::{Context, Result};
2use arrow::{array::RecordBatch, datatypes::SchemaRef};
3use arrow_flight::{
4    decode::FlightRecordBatchStream, flight_service_client::FlightServiceClient,
5    sql::client::FlightSqlServiceClient,
6};
7use futures::stream::StreamExt;
8use micromegas_telemetry::time_range::TimeRange;
9use std::sync::Arc;
10use tonic::transport::Channel;
11
12/// Represents a prepared statement with its schema and query string.
13#[derive(Debug)]
14pub struct PreparedStatement {
15    pub schema: SchemaRef,
16    pub query: String,
17}
18
19/// What the server reports about a query before running it.
20#[derive(Debug)]
21pub struct QueryEstimate {
22    pub schema: SchemaRef,
23    /// Estimated bytes the query will scan; `None` when the server reports no estimate.
24    pub total_bytes: Option<u64>,
25    /// How the estimate was obtained (e.g. `footer`, `file_size_share`, `opaque`).
26    pub estimate_precision: Option<String>,
27    /// Whether the estimate is within the caller's scan cap; `None` when not reported.
28    pub within_scan_cap: Option<bool>,
29}
30
31/// Micromegas FlightSQL client
32pub struct Client {
33    inner: FlightSqlServiceClient<Channel>,
34}
35
36impl Client {
37    /// Creates a new client from a grpc channel
38    ///
39    /// # Arguments
40    ///
41    /// * `channel` - The gRPC channel to use for communication.
42    pub fn new(channel: Channel) -> Self {
43        let flight_client =
44            FlightServiceClient::new(channel).max_decoding_message_size(100 * 1024 * 1024);
45        let inner = FlightSqlServiceClient::new_from_inner(flight_client);
46        Self { inner }
47    }
48
49    /// Returns a mutable reference to the inner `FlightSqlServiceClient`.
50    ///
51    /// This allows direct access to the underlying FlightSQL client for advanced operations.
52    pub fn inner_mut(&mut self) -> &mut FlightSqlServiceClient<Channel> {
53        &mut self.inner
54    }
55
56    fn set_query_range(&mut self, query_range: Option<TimeRange>) {
57        self.inner.set_header(
58            "query_range_begin",
59            query_range.map_or(String::from(""), |r| r.begin.to_rfc3339()),
60        );
61        self.inner.set_header(
62            "query_range_end",
63            query_range.map_or(String::from(""), |r| r.end.to_rfc3339()),
64        );
65    }
66
67    /// Executes a SQL query and returns the results as a vector of `RecordBatch`.
68    ///
69    /// # Arguments
70    ///
71    /// * `sql` - The SQL query string to execute.
72    /// * `query_range` - An optional `TimeRange` to filter the query results by time.
73    pub async fn query(
74        &mut self,
75        sql: String,
76        query_range: Option<TimeRange>,
77    ) -> Result<Vec<RecordBatch>> {
78        let mut record_batch_stream = self.query_stream(sql, query_range).await?;
79        let mut batches = vec![];
80        while let Some(batch_res) = record_batch_stream.next().await {
81            batches.push(batch_res?);
82        }
83        Ok(batches)
84    }
85
86    /// Executes a SQL query and returns the results as a `FlightRecordBatchStream`.
87    ///
88    /// This function is useful for processing large query results incrementally.
89    ///
90    /// # Arguments
91    ///
92    /// * `sql` - The SQL query string to execute.
93    /// * `query_range` - An optional `TimeRange` to filter the query results by time.
94    pub async fn query_stream(
95        &mut self,
96        sql: String,
97        query_range: Option<TimeRange>,
98    ) -> Result<FlightRecordBatchStream> {
99        self.set_query_range(query_range);
100        let info = self.inner.execute(sql, None).await?;
101        let ticket = info.endpoint[0]
102            .ticket
103            .clone()
104            .with_context(|| "reading ticket from endpoint")?;
105        let flight_data_stream = self.inner.do_get(ticket).await?.into_inner();
106        Ok(FlightRecordBatchStream::new(flight_data_stream))
107    }
108
109    /// Prepares a SQL statement and returns a `PreparedStatement`.
110    ///
111    /// This function allows to compute the schema of a query without actually executing it.
112    ///
113    /// # Arguments
114    ///
115    /// * `sql` - The SQL query string to prepare.
116    pub async fn prepare_statement(&mut self, sql: String) -> Result<PreparedStatement> {
117        self.set_query_range(None);
118        let prepared = self.inner.prepare(sql.clone(), None).await?;
119        Ok(PreparedStatement {
120            schema: Arc::new(prepared.dataset_schema()?.clone()),
121            query: sql,
122        })
123    }
124
125    /// Plans a query without running it: returns its schema and the server's scan estimate.
126    ///
127    /// The estimate fields come from `FlightInfo.total_bytes` (negative means unknown) and an
128    /// optional JSON `app_metadata` object with `estimate_precision` and `within_scan_cap`.
129    /// A server that reports none of them yields `None` for each.
130    ///
131    /// # Arguments
132    ///
133    /// * `sql` - The SQL query string to plan.
134    /// * `query_range` - An optional `TimeRange` the query would run over.
135    pub async fn prepare_query(
136        &mut self,
137        sql: String,
138        query_range: Option<TimeRange>,
139    ) -> Result<QueryEstimate> {
140        self.set_query_range(query_range);
141        let prepared = self.inner.prepare(sql.clone(), None).await?;
142        let schema = Arc::new(prepared.dataset_schema()?.clone());
143        let info = self.inner.execute(sql, None).await?;
144        let total_bytes = u64::try_from(info.total_bytes).ok();
145        let metadata: serde_json::Value =
146            serde_json::from_slice(&info.app_metadata).unwrap_or(serde_json::Value::Null);
147        Ok(QueryEstimate {
148            schema,
149            total_bytes,
150            estimate_precision: metadata
151                .get("estimate_precision")
152                .and_then(|v| v.as_str())
153                .map(str::to_string),
154            within_scan_cap: metadata.get("within_scan_cap").and_then(|v| v.as_bool()),
155        })
156    }
157}