1use arrow_buffer::Buffer;
8use arrow_ipc::MessageHeader;
9use arrow_ipc::convert::try_fb_to_schema;
10use arrow_ipc::reader::read_record_batch;
11use arrow_ipc::root_as_message;
12use arrow_schema::SchemaRef;
13use base64::Engine;
14use base64::prelude::BASE64_STANDARD;
15use bytes::Bytes;
16use std::collections::HashMap;
17use std::str::FromStr;
18use tonic::metadata::AsciiMetadataKey;
19
20use crate::decode::FlightRecordBatchStream;
21use crate::encode::FlightDataEncoderBuilder;
22use crate::error::FlightError;
23use crate::error::Result;
24use crate::flight_service_client::FlightServiceClient;
25use crate::sql::r#gen::action_end_transaction_request::EndTransaction;
26use crate::sql::server::{
27 BEGIN_TRANSACTION, CLOSE_PREPARED_STATEMENT, CREATE_PREPARED_STATEMENT, END_TRANSACTION,
28};
29use crate::sql::{
30 ActionBeginTransactionRequest, ActionBeginTransactionResult,
31 ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
32 ActionCreatePreparedStatementResult, ActionEndTransactionRequest, Any, CommandGetCatalogs,
33 CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys, CommandGetImportedKeys,
34 CommandGetPrimaryKeys, CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
35 CommandGetXdbcTypeInfo, CommandPreparedStatementQuery, CommandPreparedStatementUpdate,
36 CommandStatementIngest, CommandStatementQuery, CommandStatementUpdate,
37 DoPutPreparedStatementResult, DoPutUpdateResult, ProstMessageExt, SqlInfo,
38};
39use crate::streams::FallibleRequestStream;
40use crate::trailers::extract_lazy_trailers;
41use crate::{
42 Action, FlightData, FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse,
43 IpcMessage, PutResult, Ticket,
44};
45use arrow_array::RecordBatch;
46use arrow_schema::{ArrowError, Schema};
47use futures::{Stream, TryStreamExt, stream};
48use prost::Message;
49use tonic::codegen::{Body, StdError};
50use tonic::{IntoRequest, IntoStreamingRequest, Streaming};
51
52#[derive(Debug)]
55pub struct FlightSqlServiceClient<T> {
56 token: Option<String>,
57 headers: HashMap<String, String>,
58 flight_client: FlightServiceClient<T>,
59}
60
61impl<T> FlightSqlServiceClient<T>
65where
66 T: tonic::client::GrpcService<tonic::body::Body>,
67 T::Error: Into<StdError>,
68 T::ResponseBody: Body<Data = Bytes> + Send + 'static,
69 <T::ResponseBody as Body>::Error: Into<StdError> + Send,
70{
71 pub fn new(channel: T) -> Self {
73 Self::new_from_inner(FlightServiceClient::new(channel))
74 }
75
76 pub fn new_from_inner(inner: FlightServiceClient<T>) -> Self {
78 Self {
79 token: None,
80 flight_client: inner,
81 headers: HashMap::default(),
82 }
83 }
84
85 pub fn inner(&self) -> &FlightServiceClient<T> {
87 &self.flight_client
88 }
89
90 pub fn inner_mut(&mut self) -> &mut FlightServiceClient<T> {
92 &mut self.flight_client
93 }
94
95 pub fn into_inner(self) -> FlightServiceClient<T> {
97 self.flight_client
98 }
99
100 pub fn set_token(&mut self, token: String) {
102 self.token = Some(token);
103 }
104
105 pub fn clear_token(&mut self) {
107 self.token = None;
108 }
109
110 pub fn token(&self) -> Option<&String> {
112 self.token.as_ref()
113 }
114
115 pub fn set_header(&mut self, key: impl Into<String>, value: impl Into<String>) {
117 let key: String = key.into();
118 let value: String = value.into();
119 self.headers.insert(key, value);
120 }
121
122 async fn get_flight_info_for_command<M: ProstMessageExt>(
123 &mut self,
124 cmd: M,
125 ) -> Result<FlightInfo> {
126 let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec());
127 let req = self.set_request_headers(descriptor.into_request())?;
128 let fi = self.flight_client.get_flight_info(req).await?.into_inner();
129 Ok(fi)
130 }
131
132 pub async fn execute(
134 &mut self,
135 query: String,
136 transaction_id: Option<Bytes>,
137 ) -> Result<FlightInfo> {
138 let cmd = CommandStatementQuery {
139 query,
140 transaction_id,
141 };
142 self.get_flight_info_for_command(cmd).await
143 }
144
145 pub async fn handshake(&mut self, username: &str, password: &str) -> Result<Bytes> {
151 let cmd = HandshakeRequest {
152 protocol_version: 0,
153 payload: Default::default(),
154 };
155 let mut req = tonic::Request::new(stream::iter(vec![cmd]));
156 let val = BASE64_STANDARD.encode(format!("{username}:{password}"));
157 let val = format!("Basic {val}")
158 .parse()
159 .map_err(|_| ArrowError::ParseError("Cannot parse header".to_string()))?;
160 req.metadata_mut().insert("authorization", val);
161 let req = self.set_request_headers(req)?;
162 let resp = self
163 .flight_client
164 .handshake(req)
165 .await
166 .map_err(|e| ArrowError::IpcError(format!("Can't handshake {e}")))?;
167 if let Some(auth) = resp.metadata().get("authorization") {
168 let auth = auth
169 .to_str()
170 .map_err(|_| ArrowError::ParseError("Can't read auth header".to_string()))?;
171 let bearer = "Bearer ";
172 if !auth.starts_with(bearer) {
173 Err(ArrowError::ParseError("Invalid auth header!".to_string()))?;
174 }
175 let auth = auth[bearer.len()..].to_string();
176 self.token = Some(auth);
177 }
178 let responses: Vec<HandshakeResponse> = resp
179 .into_inner()
180 .try_collect()
181 .await
182 .map_err(|_| ArrowError::ParseError("Can't collect responses".to_string()))?;
183 let resp = match responses.as_slice() {
184 [resp] => resp.payload.clone(),
185 [] => Bytes::new(),
186 _ => Err(ArrowError::ParseError(
187 "Multiple handshake responses".to_string(),
188 ))?,
189 };
190 Ok(resp)
191 }
192
193 pub async fn execute_update(
195 &mut self,
196 query: String,
197 transaction_id: Option<Bytes>,
198 ) -> Result<i64> {
199 let cmd = CommandStatementUpdate {
200 query,
201 transaction_id,
202 };
203 let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec());
204 let req = self.set_request_headers(
205 stream::iter(vec![FlightData {
206 flight_descriptor: Some(descriptor),
207 ..Default::default()
208 }])
209 .into_request(),
210 )?;
211 let mut result = self.flight_client.do_put(req).await?.into_inner();
212 let result = result.message().await?.ok_or_else(|| {
213 FlightError::protocol("Server closed the stream without sending a result")
214 })?;
215 let result: DoPutUpdateResult = Message::decode(&*result.app_metadata)?;
216 Ok(result.record_count)
217 }
218
219 pub async fn execute_ingest<S>(
221 &mut self,
222 command: CommandStatementIngest,
223 stream: S,
224 ) -> Result<i64>
225 where
226 S: Stream<Item = crate::error::Result<RecordBatch>> + Send + 'static,
227 {
228 let (sender, receiver) = futures::channel::oneshot::channel();
229
230 let descriptor = FlightDescriptor::new_cmd(command.as_any().encode_to_vec());
231 let flight_data = FlightDataEncoderBuilder::new()
232 .with_flight_descriptor(Some(descriptor))
233 .build(stream);
234
235 let flight_data = Box::pin(flight_data);
237 let flight_data: FallibleRequestStream<FlightData, FlightError> =
238 FallibleRequestStream::new(sender, flight_data);
239
240 let req = self.set_request_headers(flight_data.into_streaming_request())?;
241 let mut result = self.flight_client.do_put(req).await?.into_inner();
242
243 if let Ok(msg) = receiver.await {
247 return Err(FlightError::ExternalError(Box::new(msg)));
248 }
249
250 let result = result.message().await?.ok_or_else(|| {
251 FlightError::protocol("Server closed the stream without sending a result")
252 })?;
253 let result: DoPutUpdateResult = Message::decode(&*result.app_metadata)?;
254 Ok(result.record_count)
255 }
256
257 pub async fn get_catalogs(&mut self) -> Result<FlightInfo> {
259 self.get_flight_info_for_command(CommandGetCatalogs {})
260 .await
261 }
262
263 pub async fn get_db_schemas(&mut self, request: CommandGetDbSchemas) -> Result<FlightInfo> {
265 self.get_flight_info_for_command(request).await
266 }
267
268 pub async fn do_get(
270 &mut self,
271 ticket: impl IntoRequest<Ticket>,
272 ) -> Result<FlightRecordBatchStream> {
273 let req = self.set_request_headers(ticket.into_request())?;
274
275 let (md, response_stream, _ext) = self.flight_client.do_get(req).await?.into_parts();
276 let (response_stream, trailers) = extract_lazy_trailers(response_stream);
277
278 Ok(FlightRecordBatchStream::new_from_flight_data(
279 response_stream.map_err(|status| status.into()),
280 )
281 .with_headers(md)
282 .with_trailers(trailers))
283 }
284
285 pub async fn do_put(
287 &mut self,
288 request: impl tonic::IntoStreamingRequest<Message = FlightData>,
289 ) -> Result<Streaming<PutResult>> {
290 let req = self.set_request_headers(request.into_streaming_request())?;
291 Ok(self.flight_client.do_put(req).await?.into_inner())
292 }
293
294 pub async fn do_action(
296 &mut self,
297 request: impl IntoRequest<Action>,
298 ) -> Result<Streaming<crate::Result>> {
299 let req = self.set_request_headers(request.into_request())?;
300 Ok(self.flight_client.do_action(req).await?.into_inner())
301 }
302
303 pub async fn get_tables(&mut self, request: CommandGetTables) -> Result<FlightInfo> {
305 self.get_flight_info_for_command(request).await
306 }
307
308 pub async fn get_primary_keys(&mut self, request: CommandGetPrimaryKeys) -> Result<FlightInfo> {
310 self.get_flight_info_for_command(request).await
311 }
312
313 pub async fn get_exported_keys(
316 &mut self,
317 request: CommandGetExportedKeys,
318 ) -> Result<FlightInfo> {
319 self.get_flight_info_for_command(request).await
320 }
321
322 pub async fn get_imported_keys(
324 &mut self,
325 request: CommandGetImportedKeys,
326 ) -> Result<FlightInfo> {
327 self.get_flight_info_for_command(request).await
328 }
329
330 pub async fn get_cross_reference(
334 &mut self,
335 request: CommandGetCrossReference,
336 ) -> Result<FlightInfo> {
337 self.get_flight_info_for_command(request).await
338 }
339
340 pub async fn get_table_types(&mut self) -> Result<FlightInfo> {
342 self.get_flight_info_for_command(CommandGetTableTypes {})
343 .await
344 }
345
346 pub async fn get_sql_info(&mut self, sql_infos: Vec<SqlInfo>) -> Result<FlightInfo> {
348 let request = CommandGetSqlInfo {
349 info: sql_infos.iter().map(|sql_info| *sql_info as u32).collect(),
350 };
351 self.get_flight_info_for_command(request).await
352 }
353
354 pub async fn get_xdbc_type_info(
356 &mut self,
357 request: CommandGetXdbcTypeInfo,
358 ) -> Result<FlightInfo> {
359 self.get_flight_info_for_command(request).await
360 }
361
362 pub async fn prepare(
364 &mut self,
365 query: String,
366 transaction_id: Option<Bytes>,
367 ) -> Result<PreparedStatement<T>>
368 where
369 T: Clone,
370 {
371 let cmd = ActionCreatePreparedStatementRequest {
372 query,
373 transaction_id,
374 };
375 let action = Action {
376 r#type: CREATE_PREPARED_STATEMENT.to_string(),
377 body: cmd.as_any().encode_to_vec().into(),
378 };
379 let req = self.set_request_headers(action.into_request())?;
380 let mut result = self.flight_client.do_action(req).await?.into_inner();
381 let result = result.message().await?.ok_or_else(|| {
382 FlightError::protocol("Server closed the stream without sending a result")
383 })?;
384 let any = Any::decode(&*result.body)?;
385 let prepared_result: ActionCreatePreparedStatementResult =
386 any.unpack()?.ok_or_else(|| {
387 FlightError::protocol(
388 "Server did not return an ActionCreatePreparedStatementResult",
389 )
390 })?;
391 let dataset_schema = match prepared_result.dataset_schema.len() {
392 0 => Schema::empty(),
393 _ => Schema::try_from(IpcMessage(prepared_result.dataset_schema))?,
394 };
395 let parameter_schema = match prepared_result.parameter_schema.len() {
396 0 => Schema::empty(),
397 _ => Schema::try_from(IpcMessage(prepared_result.parameter_schema))?,
398 };
399 Ok(PreparedStatement::new(
400 self.clone(),
401 prepared_result.prepared_statement_handle,
402 dataset_schema,
403 parameter_schema,
404 ))
405 }
406
407 pub async fn begin_transaction(&mut self) -> Result<Bytes> {
409 let cmd = ActionBeginTransactionRequest {};
410 let action = Action {
411 r#type: BEGIN_TRANSACTION.to_string(),
412 body: cmd.as_any().encode_to_vec().into(),
413 };
414 let req = self.set_request_headers(action.into_request())?;
415 let mut result = self.flight_client.do_action(req).await?.into_inner();
416 let result = result.message().await?.ok_or_else(|| {
417 FlightError::protocol("Server closed the stream without sending a result")
418 })?;
419 let any = Any::decode(&*result.body)?;
420 let begin_result: ActionBeginTransactionResult = any.unpack()?.ok_or_else(|| {
421 FlightError::protocol("Server did not return an ActionBeginTransactionResult")
422 })?;
423 Ok(begin_result.transaction_id)
424 }
425
426 pub async fn end_transaction(
428 &mut self,
429 transaction_id: Bytes,
430 action: EndTransaction,
431 ) -> Result<()> {
432 let cmd = ActionEndTransactionRequest {
433 transaction_id,
434 action: action as i32,
435 };
436 let action = Action {
437 r#type: END_TRANSACTION.to_string(),
438 body: cmd.as_any().encode_to_vec().into(),
439 };
440 let req = self.set_request_headers(action.into_request())?;
441 let _ = self.flight_client.do_action(req).await?.into_inner();
442 Ok(())
443 }
444
445 #[expect(
447 clippy::unused_async,
448 clippy::unused_async_trait_impl,
449 reason = "public API: dropping `async` would break callers that `.await` it"
450 )]
451 pub async fn close(&mut self) -> Result<()> {
452 Ok(())
454 }
455
456 fn set_request_headers<M>(&self, mut req: tonic::Request<M>) -> Result<tonic::Request<M>> {
457 for (k, v) in &self.headers {
458 let k = AsciiMetadataKey::from_str(k.as_str()).map_err(|e| {
459 ArrowError::ParseError(format!("Cannot convert header key \"{k}\": {e}"))
460 })?;
461 let v = v.parse().map_err(|e| {
462 ArrowError::ParseError(format!("Cannot convert header value \"{v}\": {e}"))
463 })?;
464 req.metadata_mut().insert(k, v);
465 }
466 if let Some(token) = &self.token {
467 let val = format!("Bearer {token}").parse().map_err(|e| {
468 ArrowError::ParseError(format!("Cannot convert token to header value: {e}"))
469 })?;
470 req.metadata_mut().insert("authorization", val);
471 }
472 Ok(req)
473 }
474}
475
476impl<T: Clone> Clone for FlightSqlServiceClient<T> {
477 fn clone(&self) -> Self {
478 Self {
479 headers: self.headers.clone(),
480 token: self.token.clone(),
481 flight_client: self.flight_client.clone(),
482 }
483 }
484}
485
486#[derive(Debug, Clone)]
488pub struct PreparedStatement<T> {
489 flight_sql_client: FlightSqlServiceClient<T>,
490 parameter_binding: Option<RecordBatch>,
491 handle: Bytes,
492 dataset_schema: Schema,
493 parameter_schema: Schema,
494}
495
496impl<T> PreparedStatement<T>
497where
498 T: tonic::client::GrpcService<tonic::body::Body>,
499 T::Error: Into<StdError>,
500 T::ResponseBody: Body<Data = Bytes> + Send + 'static,
501 <T::ResponseBody as Body>::Error: Into<StdError> + Send,
502{
503 pub(crate) fn new(
504 flight_client: FlightSqlServiceClient<T>,
505 handle: impl Into<Bytes>,
506 dataset_schema: Schema,
507 parameter_schema: Schema,
508 ) -> Self {
509 PreparedStatement {
510 flight_sql_client: flight_client,
511 parameter_binding: None,
512 handle: handle.into(),
513 dataset_schema,
514 parameter_schema,
515 }
516 }
517
518 pub async fn execute(&mut self) -> Result<FlightInfo> {
520 self.write_bind_params().await?;
521
522 let cmd = CommandPreparedStatementQuery {
523 prepared_statement_handle: self.handle.clone(),
524 };
525
526 let result = self
527 .flight_sql_client
528 .get_flight_info_for_command(cmd)
529 .await?;
530 Ok(result)
531 }
532
533 pub async fn execute_update(&mut self) -> Result<i64> {
535 self.write_bind_params().await?;
536
537 let cmd = CommandPreparedStatementUpdate {
538 prepared_statement_handle: self.handle.clone(),
539 };
540 let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec());
541 let mut result = self
542 .flight_sql_client
543 .do_put(stream::iter(vec![FlightData {
544 flight_descriptor: Some(descriptor),
545 ..Default::default()
546 }]))
547 .await?;
548 let result = result.message().await?.ok_or_else(|| {
549 FlightError::protocol("Server closed the stream without sending a result")
550 })?;
551 let result: DoPutUpdateResult = Message::decode(&*result.app_metadata)?;
552 Ok(result.record_count)
553 }
554
555 pub fn parameter_schema(&self) -> Result<&Schema> {
557 Ok(&self.parameter_schema)
558 }
559
560 pub fn dataset_schema(&self) -> Result<&Schema> {
562 Ok(&self.dataset_schema)
563 }
564
565 pub fn set_parameters(&mut self, parameter_binding: RecordBatch) -> Result<()> {
567 self.parameter_binding = Some(parameter_binding);
568 Ok(())
569 }
570
571 async fn write_bind_params(&mut self) -> Result<()> {
574 if let Some(ref params_batch) = self.parameter_binding {
575 let cmd = CommandPreparedStatementQuery {
576 prepared_statement_handle: self.handle.clone(),
577 };
578
579 let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec());
580 let flight_stream_builder = FlightDataEncoderBuilder::new()
581 .with_flight_descriptor(Some(descriptor))
582 .with_schema(params_batch.schema());
583 let flight_data = flight_stream_builder
584 .build(futures::stream::iter(
585 self.parameter_binding.clone().map(Ok),
586 ))
587 .try_collect::<Vec<_>>()
588 .await?;
589
590 if let Some(result) = self
594 .flight_sql_client
595 .do_put(stream::iter(flight_data))
596 .await?
597 .message()
598 .await?
599 && let Some(handle) = self.unpack_prepared_statement_handle(&result)?
600 {
601 self.handle = handle;
602 }
603 }
604 Ok(())
605 }
606
607 fn unpack_prepared_statement_handle(&self, put_result: &PutResult) -> Result<Option<Bytes>> {
611 let result: DoPutPreparedStatementResult = Message::decode(&*put_result.app_metadata)?;
612 Ok(result.prepared_statement_handle)
613 }
614
615 pub async fn close(mut self) -> Result<()> {
618 let cmd = ActionClosePreparedStatementRequest {
619 prepared_statement_handle: self.handle.clone(),
620 };
621 let action = Action {
622 r#type: CLOSE_PREPARED_STATEMENT.to_string(),
623 body: cmd.as_any().encode_to_vec().into(),
624 };
625 let _ = self.flight_sql_client.do_action(action).await?;
626 Ok(())
627 }
628}
629
630pub enum ArrowFlightData {
632 RecordBatch(RecordBatch),
634 Schema(Schema),
636}
637
638pub fn arrow_data_from_flight_data(
640 flight_data: FlightData,
641 arrow_schema_ref: &SchemaRef,
642) -> std::result::Result<ArrowFlightData, ArrowError> {
643 let ipc_message = root_as_message(&flight_data.data_header[..])
644 .map_err(|err| ArrowError::ParseError(format!("Unable to get root as message: {err:?}")))?;
645
646 match ipc_message.header_type() {
647 MessageHeader::RecordBatch => {
648 let ipc_record_batch = ipc_message.header_as_record_batch().ok_or_else(|| {
649 ArrowError::ComputeError(
650 "Unable to convert flight data header to a record batch".to_string(),
651 )
652 })?;
653
654 let dictionaries_by_field = HashMap::new();
655 let record_batch = read_record_batch(
656 &Buffer::from(flight_data.data_body),
657 ipc_record_batch,
658 arrow_schema_ref.clone(),
659 &dictionaries_by_field,
660 None,
661 &ipc_message.version(),
662 )?;
663 Ok(ArrowFlightData::RecordBatch(record_batch))
664 }
665 MessageHeader::Schema => {
666 let ipc_schema = ipc_message.header_as_schema().ok_or_else(|| {
667 ArrowError::ComputeError(
668 "Unable to convert flight data header to a schema".to_string(),
669 )
670 })?;
671
672 let arrow_schema = try_fb_to_schema(ipc_schema)?;
673 Ok(ArrowFlightData::Schema(arrow_schema))
674 }
675 MessageHeader::DictionaryBatch => {
676 let _ = ipc_message.header_as_dictionary_batch().ok_or_else(|| {
677 ArrowError::ComputeError(
678 "Unable to convert flight data header to a dictionary batch".to_string(),
679 )
680 })?;
681 Err(ArrowError::NotYetImplemented(
682 "no idea on how to convert an ipc dictionary batch to an arrow type".to_string(),
683 ))
684 }
685 MessageHeader::Tensor => {
686 let _ = ipc_message.header_as_tensor().ok_or_else(|| {
687 ArrowError::ComputeError(
688 "Unable to convert flight data header to a tensor".to_string(),
689 )
690 })?;
691 Err(ArrowError::NotYetImplemented(
692 "no idea on how to convert an ipc tensor to an arrow type".to_string(),
693 ))
694 }
695 MessageHeader::SparseTensor => {
696 let _ = ipc_message.header_as_sparse_tensor().ok_or_else(|| {
697 ArrowError::ComputeError(
698 "Unable to convert flight data header to a sparse tensor".to_string(),
699 )
700 })?;
701 Err(ArrowError::NotYetImplemented(
702 "no idea on how to convert an ipc sparse tensor to an arrow type".to_string(),
703 ))
704 }
705 _ => Err(ArrowError::ComputeError(format!(
706 "Unable to convert message with header_type: '{:?}' to arrow data",
707 ipc_message.header_type()
708 ))),
709 }
710}