1use std::fmt::{Display, Formatter};
8use std::pin::Pin;
9
10use super::{
11 ActionBeginSavepointRequest, ActionBeginSavepointResult, ActionBeginTransactionRequest,
12 ActionBeginTransactionResult, ActionCancelQueryRequest, ActionCancelQueryResult,
13 ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
14 ActionCreatePreparedStatementResult, ActionCreatePreparedSubstraitPlanRequest,
15 ActionEndSavepointRequest, ActionEndTransactionRequest, Any, Command, CommandGetCatalogs,
16 CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys, CommandGetImportedKeys,
17 CommandGetPrimaryKeys, CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
18 CommandGetXdbcTypeInfo, CommandPreparedStatementQuery, CommandPreparedStatementUpdate,
19 CommandStatementIngest, CommandStatementQuery, CommandStatementSubstraitPlan,
20 CommandStatementUpdate, DoPutPreparedStatementResult, DoPutUpdateResult, ProstMessageExt,
21 SqlInfo, TicketStatementQuery,
22};
23use crate::{
24 Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightInfo,
25 HandshakeRequest, HandshakeResponse, PutResult, SchemaResult, Ticket,
26 flight_service_server::FlightService, r#gen::PollInfo,
27};
28use futures::{Stream, StreamExt, stream::Peekable};
29use prost::Message;
30use tonic::{Request, Response, Status, Streaming};
31
32pub(crate) static CREATE_PREPARED_STATEMENT: &str = "CreatePreparedStatement";
33pub(crate) static CLOSE_PREPARED_STATEMENT: &str = "ClosePreparedStatement";
34pub(crate) static CREATE_PREPARED_SUBSTRAIT_PLAN: &str = "CreatePreparedSubstraitPlan";
35pub(crate) static BEGIN_TRANSACTION: &str = "BeginTransaction";
36pub(crate) static END_TRANSACTION: &str = "EndTransaction";
37pub(crate) static BEGIN_SAVEPOINT: &str = "BeginSavepoint";
38pub(crate) static END_SAVEPOINT: &str = "EndSavepoint";
39pub(crate) static CANCEL_QUERY: &str = "CancelQuery";
40
41#[tonic::async_trait]
43pub trait FlightSqlService: Sync + Send + Sized + 'static {
44 type FlightService: FlightService;
46
47 async fn do_handshake(
50 &self,
51 _request: Request<Streaming<HandshakeRequest>>,
52 ) -> Result<
53 Response<Pin<Box<dyn Stream<Item = Result<HandshakeResponse, Status>> + Send>>>,
54 Status,
55 > {
56 Err(Status::unimplemented(
57 "Handshake has no default implementation",
58 ))
59 }
60
61 async fn do_get_fallback(
63 &self,
64 _request: Request<Ticket>,
65 message: Any,
66 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
67 Err(Status::unimplemented(format!(
68 "do_get: The defined request is invalid: {}",
69 message.type_url
70 )))
71 }
72
73 async fn get_flight_info_statement(
75 &self,
76 _query: CommandStatementQuery,
77 _request: Request<FlightDescriptor>,
78 ) -> Result<Response<FlightInfo>, Status> {
79 Err(Status::unimplemented(
80 "get_flight_info_statement has no default implementation",
81 ))
82 }
83
84 async fn get_flight_info_substrait_plan(
86 &self,
87 _query: CommandStatementSubstraitPlan,
88 _request: Request<FlightDescriptor>,
89 ) -> Result<Response<FlightInfo>, Status> {
90 Err(Status::unimplemented(
91 "get_flight_info_substrait_plan has no default implementation",
92 ))
93 }
94
95 async fn get_flight_info_prepared_statement(
97 &self,
98 _query: CommandPreparedStatementQuery,
99 _request: Request<FlightDescriptor>,
100 ) -> Result<Response<FlightInfo>, Status> {
101 Err(Status::unimplemented(
102 "get_flight_info_prepared_statement has no default implementation",
103 ))
104 }
105
106 async fn get_flight_info_catalogs(
108 &self,
109 _query: CommandGetCatalogs,
110 _request: Request<FlightDescriptor>,
111 ) -> Result<Response<FlightInfo>, Status> {
112 Err(Status::unimplemented(
113 "get_flight_info_catalogs has no default implementation",
114 ))
115 }
116
117 async fn get_flight_info_schemas(
119 &self,
120 _query: CommandGetDbSchemas,
121 _request: Request<FlightDescriptor>,
122 ) -> Result<Response<FlightInfo>, Status> {
123 Err(Status::unimplemented(
124 "get_flight_info_schemas has no default implementation",
125 ))
126 }
127
128 async fn get_flight_info_tables(
130 &self,
131 _query: CommandGetTables,
132 _request: Request<FlightDescriptor>,
133 ) -> Result<Response<FlightInfo>, Status> {
134 Err(Status::unimplemented(
135 "get_flight_info_tables has no default implementation",
136 ))
137 }
138
139 async fn get_flight_info_table_types(
141 &self,
142 _query: CommandGetTableTypes,
143 _request: Request<FlightDescriptor>,
144 ) -> Result<Response<FlightInfo>, Status> {
145 Err(Status::unimplemented(
146 "get_flight_info_table_types has no default implementation",
147 ))
148 }
149
150 async fn get_flight_info_sql_info(
152 &self,
153 _query: CommandGetSqlInfo,
154 _request: Request<FlightDescriptor>,
155 ) -> Result<Response<FlightInfo>, Status> {
156 Err(Status::unimplemented(
157 "get_flight_info_sql_info has no default implementation",
158 ))
159 }
160
161 async fn get_flight_info_primary_keys(
163 &self,
164 _query: CommandGetPrimaryKeys,
165 _request: Request<FlightDescriptor>,
166 ) -> Result<Response<FlightInfo>, Status> {
167 Err(Status::unimplemented(
168 "get_flight_info_primary_keys has no default implementation",
169 ))
170 }
171
172 async fn get_flight_info_exported_keys(
174 &self,
175 _query: CommandGetExportedKeys,
176 _request: Request<FlightDescriptor>,
177 ) -> Result<Response<FlightInfo>, Status> {
178 Err(Status::unimplemented(
179 "get_flight_info_exported_keys has no default implementation",
180 ))
181 }
182
183 async fn get_flight_info_imported_keys(
185 &self,
186 _query: CommandGetImportedKeys,
187 _request: Request<FlightDescriptor>,
188 ) -> Result<Response<FlightInfo>, Status> {
189 Err(Status::unimplemented(
190 "get_flight_info_imported_keys has no default implementation",
191 ))
192 }
193
194 async fn get_flight_info_cross_reference(
196 &self,
197 _query: CommandGetCrossReference,
198 _request: Request<FlightDescriptor>,
199 ) -> Result<Response<FlightInfo>, Status> {
200 Err(Status::unimplemented(
201 "get_flight_info_cross_reference has no default implementation",
202 ))
203 }
204
205 async fn get_flight_info_xdbc_type_info(
207 &self,
208 _query: CommandGetXdbcTypeInfo,
209 _request: Request<FlightDescriptor>,
210 ) -> Result<Response<FlightInfo>, Status> {
211 Err(Status::unimplemented(
212 "get_flight_info_xdbc_type_info has no default implementation",
213 ))
214 }
215
216 async fn get_flight_info_fallback(
218 &self,
219 cmd: Command,
220 _request: Request<FlightDescriptor>,
221 ) -> Result<Response<FlightInfo>, Status> {
222 Err(Status::unimplemented(format!(
223 "get_flight_info: The defined request is invalid: {}",
224 cmd.type_url()
225 )))
226 }
227
228 async fn do_get_statement(
232 &self,
233 _ticket: TicketStatementQuery,
234 _request: Request<Ticket>,
235 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
236 Err(Status::unimplemented(
237 "do_get_statement has no default implementation",
238 ))
239 }
240
241 async fn do_get_prepared_statement(
243 &self,
244 _query: CommandPreparedStatementQuery,
245 _request: Request<Ticket>,
246 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
247 Err(Status::unimplemented(
248 "do_get_prepared_statement has no default implementation",
249 ))
250 }
251
252 async fn do_get_catalogs(
254 &self,
255 _query: CommandGetCatalogs,
256 _request: Request<Ticket>,
257 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
258 Err(Status::unimplemented(
259 "do_get_catalogs has no default implementation",
260 ))
261 }
262
263 async fn do_get_schemas(
265 &self,
266 _query: CommandGetDbSchemas,
267 _request: Request<Ticket>,
268 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
269 Err(Status::unimplemented(
270 "do_get_schemas has no default implementation",
271 ))
272 }
273
274 async fn do_get_tables(
276 &self,
277 _query: CommandGetTables,
278 _request: Request<Ticket>,
279 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
280 Err(Status::unimplemented(
281 "do_get_tables has no default implementation",
282 ))
283 }
284
285 async fn do_get_table_types(
287 &self,
288 _query: CommandGetTableTypes,
289 _request: Request<Ticket>,
290 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
291 Err(Status::unimplemented(
292 "do_get_table_types has no default implementation",
293 ))
294 }
295
296 async fn do_get_sql_info(
298 &self,
299 _query: CommandGetSqlInfo,
300 _request: Request<Ticket>,
301 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
302 Err(Status::unimplemented(
303 "do_get_sql_info has no default implementation",
304 ))
305 }
306
307 async fn do_get_primary_keys(
309 &self,
310 _query: CommandGetPrimaryKeys,
311 _request: Request<Ticket>,
312 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
313 Err(Status::unimplemented(
314 "do_get_primary_keys has no default implementation",
315 ))
316 }
317
318 async fn do_get_exported_keys(
320 &self,
321 _query: CommandGetExportedKeys,
322 _request: Request<Ticket>,
323 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
324 Err(Status::unimplemented(
325 "do_get_exported_keys has no default implementation",
326 ))
327 }
328
329 async fn do_get_imported_keys(
331 &self,
332 _query: CommandGetImportedKeys,
333 _request: Request<Ticket>,
334 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
335 Err(Status::unimplemented(
336 "do_get_imported_keys has no default implementation",
337 ))
338 }
339
340 async fn do_get_cross_reference(
342 &self,
343 _query: CommandGetCrossReference,
344 _request: Request<Ticket>,
345 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
346 Err(Status::unimplemented(
347 "do_get_cross_reference has no default implementation",
348 ))
349 }
350
351 async fn do_get_xdbc_type_info(
353 &self,
354 _query: CommandGetXdbcTypeInfo,
355 _request: Request<Ticket>,
356 ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
357 Err(Status::unimplemented(
358 "do_get_xdbc_type_info has no default implementation",
359 ))
360 }
361
362 async fn do_put_fallback(
366 &self,
367 _request: Request<PeekableFlightDataStream>,
368 message: Any,
369 ) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
370 Err(Status::unimplemented(format!(
371 "do_put: The defined request is invalid: {}",
372 message.type_url
373 )))
374 }
375
376 async fn do_put_error_callback(
378 &self,
379 _request: Request<PeekableFlightDataStream>,
380 error: DoPutError,
381 ) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
382 Err(Status::unimplemented(format!("Unhandled Error: {error}")))
383 }
384
385 async fn do_put_statement_update(
387 &self,
388 _ticket: CommandStatementUpdate,
389 _request: Request<PeekableFlightDataStream>,
390 ) -> Result<i64, Status> {
391 Err(Status::unimplemented(
392 "do_put_statement_update has no default implementation",
393 ))
394 }
395
396 async fn do_put_statement_ingest(
398 &self,
399 _ticket: CommandStatementIngest,
400 _request: Request<PeekableFlightDataStream>,
401 ) -> Result<i64, Status> {
402 Err(Status::unimplemented(
403 "do_put_statement_ingest has no default implementation",
404 ))
405 }
406
407 async fn do_put_prepared_statement_query(
413 &self,
414 _query: CommandPreparedStatementQuery,
415 _request: Request<PeekableFlightDataStream>,
416 ) -> Result<DoPutPreparedStatementResult, Status> {
417 Err(Status::unimplemented(
418 "do_put_prepared_statement_query has no default implementation",
419 ))
420 }
421
422 async fn do_put_prepared_statement_update(
424 &self,
425 _query: CommandPreparedStatementUpdate,
426 _request: Request<PeekableFlightDataStream>,
427 ) -> Result<i64, Status> {
428 Err(Status::unimplemented(
429 "do_put_prepared_statement_update has no default implementation",
430 ))
431 }
432
433 async fn do_put_substrait_plan(
435 &self,
436 _query: CommandStatementSubstraitPlan,
437 _request: Request<PeekableFlightDataStream>,
438 ) -> Result<i64, Status> {
439 Err(Status::unimplemented(
440 "do_put_substrait_plan has no default implementation",
441 ))
442 }
443
444 async fn do_action_fallback(
448 &self,
449 request: Request<Action>,
450 ) -> Result<Response<<Self as FlightService>::DoActionStream>, Status> {
451 Err(Status::invalid_argument(format!(
452 "do_action: The defined request is invalid: {:?}",
453 request.get_ref().r#type
454 )))
455 }
456
457 async fn list_custom_actions(&self) -> Option<Vec<Result<ActionType, Status>>> {
459 None
460 }
461
462 async fn do_action_create_prepared_statement(
464 &self,
465 _query: ActionCreatePreparedStatementRequest,
466 _request: Request<Action>,
467 ) -> Result<ActionCreatePreparedStatementResult, Status> {
468 Err(Status::unimplemented(
469 "do_action_create_prepared_statement has no default implementation",
470 ))
471 }
472
473 async fn do_action_close_prepared_statement(
475 &self,
476 _query: ActionClosePreparedStatementRequest,
477 _request: Request<Action>,
478 ) -> Result<(), Status> {
479 Err(Status::unimplemented(
480 "do_action_close_prepared_statement has no default implementation",
481 ))
482 }
483
484 async fn do_action_create_prepared_substrait_plan(
486 &self,
487 _query: ActionCreatePreparedSubstraitPlanRequest,
488 _request: Request<Action>,
489 ) -> Result<ActionCreatePreparedStatementResult, Status> {
490 Err(Status::unimplemented(
491 "do_action_create_prepared_substrait_plan has no default implementation",
492 ))
493 }
494
495 async fn do_action_begin_transaction(
497 &self,
498 _query: ActionBeginTransactionRequest,
499 _request: Request<Action>,
500 ) -> Result<ActionBeginTransactionResult, Status> {
501 Err(Status::unimplemented(
502 "do_action_begin_transaction has no default implementation",
503 ))
504 }
505
506 async fn do_action_end_transaction(
508 &self,
509 _query: ActionEndTransactionRequest,
510 _request: Request<Action>,
511 ) -> Result<(), Status> {
512 Err(Status::unimplemented(
513 "do_action_end_transaction has no default implementation",
514 ))
515 }
516
517 async fn do_action_begin_savepoint(
519 &self,
520 _query: ActionBeginSavepointRequest,
521 _request: Request<Action>,
522 ) -> Result<ActionBeginSavepointResult, Status> {
523 Err(Status::unimplemented(
524 "do_action_begin_savepoint has no default implementation",
525 ))
526 }
527
528 async fn do_action_end_savepoint(
530 &self,
531 _query: ActionEndSavepointRequest,
532 _request: Request<Action>,
533 ) -> Result<(), Status> {
534 Err(Status::unimplemented(
535 "do_action_end_savepoint has no default implementation",
536 ))
537 }
538
539 async fn do_action_cancel_query(
541 &self,
542 _query: ActionCancelQueryRequest,
543 _request: Request<Action>,
544 ) -> Result<ActionCancelQueryResult, Status> {
545 Err(Status::unimplemented(
546 "do_action_cancel_query has no default implementation",
547 ))
548 }
549
550 async fn do_exchange_fallback(
553 &self,
554 _request: Request<Streaming<FlightData>>,
555 ) -> Result<Response<<Self as FlightService>::DoExchangeStream>, Status> {
556 Err(Status::unimplemented("Not yet implemented"))
557 }
558
559 #[deprecated(
561 since = "60.1.0",
562 note = "Not used in request handling and doesn't accept a value to register. Use `SqlInfoDataBuilder::append` instead"
563 )]
564 async fn register_sql_info(&self, _id: i32, _result: &SqlInfo) {}
565}
566
567#[tonic::async_trait]
569impl<T: 'static> FlightService for T
570where
571 T: FlightSqlService + Send,
572{
573 type HandshakeStream =
574 Pin<Box<dyn Stream<Item = Result<HandshakeResponse, Status>> + Send + 'static>>;
575 type ListFlightsStream =
576 Pin<Box<dyn Stream<Item = Result<FlightInfo, Status>> + Send + 'static>>;
577 type DoGetStream = Pin<Box<dyn Stream<Item = Result<FlightData, Status>> + Send + 'static>>;
578 type DoPutStream = Pin<Box<dyn Stream<Item = Result<PutResult, Status>> + Send + 'static>>;
579 type DoActionStream =
580 Pin<Box<dyn Stream<Item = Result<super::super::Result, Status>> + Send + 'static>>;
581 type ListActionsStream =
582 Pin<Box<dyn Stream<Item = Result<ActionType, Status>> + Send + 'static>>;
583 type DoExchangeStream =
584 Pin<Box<dyn Stream<Item = Result<FlightData, Status>> + Send + 'static>>;
585
586 async fn handshake(
587 &self,
588 request: Request<Streaming<HandshakeRequest>>,
589 ) -> Result<Response<Self::HandshakeStream>, Status> {
590 let res = self.do_handshake(request).await?;
591 Ok(res)
592 }
593
594 async fn list_flights(
595 &self,
596 _request: Request<Criteria>,
597 ) -> Result<Response<Self::ListFlightsStream>, Status> {
598 Err(Status::unimplemented("Not yet implemented"))
599 }
600
601 async fn get_flight_info(
602 &self,
603 request: Request<FlightDescriptor>,
604 ) -> Result<Response<FlightInfo>, Status> {
605 let message = Any::decode(&*request.get_ref().cmd).map_err(decode_error_to_status)?;
606
607 match Command::try_from(message).map_err(arrow_error_to_status)? {
608 Command::CommandStatementQuery(token) => {
609 self.get_flight_info_statement(token, request).await
610 }
611 Command::CommandPreparedStatementQuery(handle) => {
612 self.get_flight_info_prepared_statement(handle, request)
613 .await
614 }
615 Command::CommandStatementSubstraitPlan(handle) => {
616 self.get_flight_info_substrait_plan(handle, request).await
617 }
618 Command::CommandGetCatalogs(token) => {
619 self.get_flight_info_catalogs(token, request).await
620 }
621 Command::CommandGetDbSchemas(token) => {
622 return self.get_flight_info_schemas(token, request).await;
623 }
624 Command::CommandGetTables(token) => self.get_flight_info_tables(token, request).await,
625 Command::CommandGetTableTypes(token) => {
626 self.get_flight_info_table_types(token, request).await
627 }
628 Command::CommandGetSqlInfo(token) => {
629 self.get_flight_info_sql_info(token, request).await
630 }
631 Command::CommandGetPrimaryKeys(token) => {
632 self.get_flight_info_primary_keys(token, request).await
633 }
634 Command::CommandGetExportedKeys(token) => {
635 self.get_flight_info_exported_keys(token, request).await
636 }
637 Command::CommandGetImportedKeys(token) => {
638 self.get_flight_info_imported_keys(token, request).await
639 }
640 Command::CommandGetCrossReference(token) => {
641 self.get_flight_info_cross_reference(token, request).await
642 }
643 Command::CommandGetXdbcTypeInfo(token) => {
644 self.get_flight_info_xdbc_type_info(token, request).await
645 }
646 cmd => self.get_flight_info_fallback(cmd, request).await,
647 }
648 }
649
650 async fn poll_flight_info(
651 &self,
652 _request: Request<FlightDescriptor>,
653 ) -> Result<Response<PollInfo>, Status> {
654 Err(Status::unimplemented("Not yet implemented"))
655 }
656
657 async fn get_schema(
658 &self,
659 _request: Request<FlightDescriptor>,
660 ) -> Result<Response<SchemaResult>, Status> {
661 Err(Status::unimplemented("Not yet implemented"))
662 }
663
664 async fn do_get(
665 &self,
666 request: Request<Ticket>,
667 ) -> Result<Response<Self::DoGetStream>, Status> {
668 let msg: Any =
669 Message::decode(&*request.get_ref().ticket).map_err(decode_error_to_status)?;
670
671 match Command::try_from(msg).map_err(arrow_error_to_status)? {
672 Command::TicketStatementQuery(command) => self.do_get_statement(command, request).await,
673 Command::CommandPreparedStatementQuery(command) => {
674 self.do_get_prepared_statement(command, request).await
675 }
676 Command::CommandGetCatalogs(command) => self.do_get_catalogs(command, request).await,
677 Command::CommandGetDbSchemas(command) => self.do_get_schemas(command, request).await,
678 Command::CommandGetTables(command) => self.do_get_tables(command, request).await,
679 Command::CommandGetTableTypes(command) => {
680 self.do_get_table_types(command, request).await
681 }
682 Command::CommandGetSqlInfo(command) => self.do_get_sql_info(command, request).await,
683 Command::CommandGetPrimaryKeys(command) => {
684 self.do_get_primary_keys(command, request).await
685 }
686 Command::CommandGetExportedKeys(command) => {
687 self.do_get_exported_keys(command, request).await
688 }
689 Command::CommandGetImportedKeys(command) => {
690 self.do_get_imported_keys(command, request).await
691 }
692 Command::CommandGetCrossReference(command) => {
693 self.do_get_cross_reference(command, request).await
694 }
695 Command::CommandGetXdbcTypeInfo(command) => {
696 self.do_get_xdbc_type_info(command, request).await
697 }
698 cmd => self.do_get_fallback(request, cmd.into_any()).await,
699 }
700 }
701
702 async fn do_put(
703 &self,
704 request: Request<Streaming<FlightData>>,
705 ) -> Result<Response<Self::DoPutStream>, Status> {
706 let mut request = request.map(PeekableFlightDataStream::new);
713 let mut stream = Pin::new(request.get_mut());
714
715 let peeked_item = stream.peek().await.cloned();
716 let Some(cmd) = peeked_item else {
717 return self
718 .do_put_error_callback(request, DoPutError::MissingCommand)
719 .await;
720 };
721
722 let Some(flight_descriptor) = cmd?.flight_descriptor else {
723 return self
724 .do_put_error_callback(request, DoPutError::MissingFlightDescriptor)
725 .await;
726 };
727 let message = Any::decode(flight_descriptor.cmd).map_err(decode_error_to_status)?;
728 match Command::try_from(message).map_err(arrow_error_to_status)? {
729 Command::CommandStatementUpdate(command) => {
730 let record_count = self.do_put_statement_update(command, request).await?;
731 let result = DoPutUpdateResult { record_count };
732 let output = futures::stream::iter(vec![Ok(PutResult {
733 app_metadata: result.encode_to_vec().into(),
734 })]);
735 Ok(Response::new(Box::pin(output)))
736 }
737 Command::CommandStatementIngest(command) => {
738 let record_count = self.do_put_statement_ingest(command, request).await?;
739 let result = DoPutUpdateResult { record_count };
740 let output = futures::stream::iter(vec![Ok(PutResult {
741 app_metadata: result.encode_to_vec().into(),
742 })]);
743 Ok(Response::new(Box::pin(output)))
744 }
745 Command::CommandPreparedStatementQuery(command) => {
746 let result = self
747 .do_put_prepared_statement_query(command, request)
748 .await?;
749 let output = futures::stream::iter(vec![Ok(PutResult {
750 app_metadata: result.encode_to_vec().into(),
751 })]);
752 Ok(Response::new(Box::pin(output)))
753 }
754 Command::CommandStatementSubstraitPlan(command) => {
755 let record_count = self.do_put_substrait_plan(command, request).await?;
756 let result = DoPutUpdateResult { record_count };
757 let output = futures::stream::iter(vec![Ok(PutResult {
758 app_metadata: result.encode_to_vec().into(),
759 })]);
760 Ok(Response::new(Box::pin(output)))
761 }
762 Command::CommandPreparedStatementUpdate(command) => {
763 let record_count = self
764 .do_put_prepared_statement_update(command, request)
765 .await?;
766 let result = DoPutUpdateResult { record_count };
767 let output = futures::stream::iter(vec![Ok(PutResult {
768 app_metadata: result.encode_to_vec().into(),
769 })]);
770 Ok(Response::new(Box::pin(output)))
771 }
772 cmd => self.do_put_fallback(request, cmd.into_any()).await,
773 }
774 }
775
776 async fn list_actions(
777 &self,
778 _request: Request<Empty>,
779 ) -> Result<Response<Self::ListActionsStream>, Status> {
780 let create_prepared_statement_action_type = ActionType {
781 r#type: CREATE_PREPARED_STATEMENT.to_string(),
782 description: "Creates a reusable prepared statement resource on the server.\n
783 Request Message: ActionCreatePreparedStatementRequest\n
784 Response Message: ActionCreatePreparedStatementResult"
785 .into(),
786 };
787 let close_prepared_statement_action_type = ActionType {
788 r#type: CLOSE_PREPARED_STATEMENT.to_string(),
789 description: "Closes a reusable prepared statement resource on the server.\n
790 Request Message: ActionClosePreparedStatementRequest\n
791 Response Message: N/A"
792 .into(),
793 };
794 let create_prepared_substrait_plan_action_type = ActionType {
795 r#type: CREATE_PREPARED_SUBSTRAIT_PLAN.to_string(),
796 description: "Creates a reusable prepared substrait plan resource on the server.\n
797 Request Message: ActionCreatePreparedSubstraitPlanRequest\n
798 Response Message: ActionCreatePreparedStatementResult"
799 .into(),
800 };
801 let begin_transaction_action_type = ActionType {
802 r#type: BEGIN_TRANSACTION.to_string(),
803 description: "Begins a transaction.\n
804 Request Message: ActionBeginTransactionRequest\n
805 Response Message: ActionBeginTransactionResult"
806 .into(),
807 };
808 let end_transaction_action_type = ActionType {
809 r#type: END_TRANSACTION.to_string(),
810 description: "Ends a transaction\n
811 Request Message: ActionEndTransactionRequest\n
812 Response Message: N/A"
813 .into(),
814 };
815 let begin_savepoint_action_type = ActionType {
816 r#type: BEGIN_SAVEPOINT.to_string(),
817 description: "Begins a savepoint.\n
818 Request Message: ActionBeginSavepointRequest\n
819 Response Message: ActionBeginSavepointResult"
820 .into(),
821 };
822 let end_savepoint_action_type = ActionType {
823 r#type: END_SAVEPOINT.to_string(),
824 description: "Ends a savepoint\n
825 Request Message: ActionEndSavepointRequest\n
826 Response Message: N/A"
827 .into(),
828 };
829 let cancel_query_action_type = ActionType {
830 r#type: CANCEL_QUERY.to_string(),
831 description: "Cancels a query\n
832 Request Message: ActionCancelQueryRequest\n
833 Response Message: ActionCancelQueryResult"
834 .into(),
835 };
836 let mut actions: Vec<Result<ActionType, Status>> = vec![
837 Ok(create_prepared_statement_action_type),
838 Ok(close_prepared_statement_action_type),
839 Ok(create_prepared_substrait_plan_action_type),
840 Ok(begin_transaction_action_type),
841 Ok(end_transaction_action_type),
842 Ok(begin_savepoint_action_type),
843 Ok(end_savepoint_action_type),
844 Ok(cancel_query_action_type),
845 ];
846
847 if let Some(mut custom_actions) = self.list_custom_actions().await {
848 actions.append(&mut custom_actions);
849 }
850
851 let output = futures::stream::iter(actions);
852 Ok(Response::new(Box::pin(output) as Self::ListActionsStream))
853 }
854
855 async fn do_action(
856 &self,
857 request: Request<Action>,
858 ) -> Result<Response<Self::DoActionStream>, Status> {
859 if request.get_ref().r#type == CREATE_PREPARED_STATEMENT {
860 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
861
862 let cmd: ActionCreatePreparedStatementRequest = any
863 .unpack()
864 .map_err(arrow_error_to_status)?
865 .ok_or_else(|| {
866 Status::invalid_argument(
867 "Unable to unpack ActionCreatePreparedStatementRequest.",
868 )
869 })?;
870 let stmt = self
871 .do_action_create_prepared_statement(cmd, request)
872 .await?;
873 let output = futures::stream::iter(vec![Ok(super::super::r#gen::Result {
874 body: stmt.as_any().encode_to_vec().into(),
875 })]);
876 return Ok(Response::new(Box::pin(output)));
877 } else if request.get_ref().r#type == CLOSE_PREPARED_STATEMENT {
878 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
879
880 let cmd: ActionClosePreparedStatementRequest = any
881 .unpack()
882 .map_err(arrow_error_to_status)?
883 .ok_or_else(|| {
884 Status::invalid_argument(
885 "Unable to unpack ActionClosePreparedStatementRequest.",
886 )
887 })?;
888 self.do_action_close_prepared_statement(cmd, request)
889 .await?;
890 return Ok(Response::new(Box::pin(futures::stream::empty())));
891 } else if request.get_ref().r#type == CREATE_PREPARED_SUBSTRAIT_PLAN {
892 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
893
894 let cmd: ActionCreatePreparedSubstraitPlanRequest = any
895 .unpack()
896 .map_err(arrow_error_to_status)?
897 .ok_or_else(|| {
898 Status::invalid_argument(
899 "Unable to unpack ActionCreatePreparedSubstraitPlanRequest.",
900 )
901 })?;
902 self.do_action_create_prepared_substrait_plan(cmd, request)
903 .await?;
904 return Ok(Response::new(Box::pin(futures::stream::empty())));
905 } else if request.get_ref().r#type == BEGIN_TRANSACTION {
906 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
907
908 let cmd: ActionBeginTransactionRequest = any
909 .unpack()
910 .map_err(arrow_error_to_status)?
911 .ok_or_else(|| {
912 Status::invalid_argument("Unable to unpack ActionBeginTransactionRequest.")
913 })?;
914 let stmt = self.do_action_begin_transaction(cmd, request).await?;
915 let output = futures::stream::iter(vec![Ok(super::super::r#gen::Result {
916 body: stmt.as_any().encode_to_vec().into(),
917 })]);
918 return Ok(Response::new(Box::pin(output)));
919 } else if request.get_ref().r#type == END_TRANSACTION {
920 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
921
922 let cmd: ActionEndTransactionRequest = any
923 .unpack()
924 .map_err(arrow_error_to_status)?
925 .ok_or_else(|| {
926 Status::invalid_argument("Unable to unpack ActionEndTransactionRequest.")
927 })?;
928 self.do_action_end_transaction(cmd, request).await?;
929 return Ok(Response::new(Box::pin(futures::stream::empty())));
930 } else if request.get_ref().r#type == BEGIN_SAVEPOINT {
931 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
932
933 let cmd: ActionBeginSavepointRequest = any
934 .unpack()
935 .map_err(arrow_error_to_status)?
936 .ok_or_else(|| {
937 Status::invalid_argument("Unable to unpack ActionBeginSavepointRequest.")
938 })?;
939 let stmt = self.do_action_begin_savepoint(cmd, request).await?;
940 let output = futures::stream::iter(vec![Ok(super::super::r#gen::Result {
941 body: stmt.as_any().encode_to_vec().into(),
942 })]);
943 return Ok(Response::new(Box::pin(output)));
944 } else if request.get_ref().r#type == END_SAVEPOINT {
945 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
946
947 let cmd: ActionEndSavepointRequest = any
948 .unpack()
949 .map_err(arrow_error_to_status)?
950 .ok_or_else(|| {
951 Status::invalid_argument("Unable to unpack ActionEndSavepointRequest.")
952 })?;
953 self.do_action_end_savepoint(cmd, request).await?;
954 return Ok(Response::new(Box::pin(futures::stream::empty())));
955 } else if request.get_ref().r#type == CANCEL_QUERY {
956 let any = Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
957
958 let cmd: ActionCancelQueryRequest = any
959 .unpack()
960 .map_err(arrow_error_to_status)?
961 .ok_or_else(|| {
962 Status::invalid_argument("Unable to unpack ActionCancelQueryRequest.")
963 })?;
964 let stmt = self.do_action_cancel_query(cmd, request).await?;
965 let output = futures::stream::iter(vec![Ok(super::super::r#gen::Result {
966 body: stmt.as_any().encode_to_vec().into(),
967 })]);
968 return Ok(Response::new(Box::pin(output)));
969 }
970
971 self.do_action_fallback(request).await
972 }
973
974 async fn do_exchange(
975 &self,
976 request: Request<Streaming<FlightData>>,
977 ) -> Result<Response<Self::DoExchangeStream>, Status> {
978 self.do_exchange_fallback(request).await
979 }
980}
981
982pub enum DoPutError {
984 MissingCommand,
986 MissingFlightDescriptor,
988}
989impl Display for DoPutError {
990 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
991 match self {
992 DoPutError::MissingCommand => {
993 write!(f, "Command is missing.")
994 }
995 DoPutError::MissingFlightDescriptor => {
996 write!(f, "Flight descriptor is missing.")
997 }
998 }
999 }
1000}
1001
1002fn decode_error_to_status(err: prost::DecodeError) -> Status {
1003 Status::invalid_argument(format!("{err:?}"))
1004}
1005
1006fn arrow_error_to_status(err: arrow_schema::ArrowError) -> Status {
1007 Status::internal(format!("{err:?}"))
1008}
1009
1010pub struct PeekableFlightDataStream {
1056 inner: Peekable<Streaming<FlightData>>,
1057}
1058
1059impl PeekableFlightDataStream {
1060 fn new(stream: Streaming<FlightData>) -> Self {
1061 Self {
1062 inner: stream.peekable(),
1063 }
1064 }
1065
1066 pub fn into_inner(self) -> Streaming<FlightData> {
1070 self.inner.into_inner()
1071 }
1072
1073 pub fn into_peekable(self) -> Peekable<Streaming<FlightData>> {
1077 self.inner
1078 }
1079
1080 pub async fn peek(&mut self) -> Option<&Result<FlightData, Status>> {
1082 Pin::new(&mut self.inner).peek().await
1083 }
1084}
1085
1086impl Stream for PeekableFlightDataStream {
1087 type Item = Result<FlightData, Status>;
1088
1089 fn poll_next(
1090 mut self: Pin<&mut Self>,
1091 cx: &mut std::task::Context<'_>,
1092 ) -> std::task::Poll<Option<Self::Item>> {
1093 self.inner.poll_next_unpin(cx)
1094 }
1095}