/
flight_sql.rs
1003 lines (939 loc) · 36.8 KB
/
flight_sql.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use arrow_flight::flight_descriptor::DescriptorType;
use arrow_flight::flight_service_server::FlightService;
use arrow_flight::sql::server::{FlightSqlService, PeekableFlightDataStream};
use arrow_flight::sql::{
ActionBeginSavepointRequest, ActionBeginSavepointResult,
ActionBeginTransactionRequest, ActionBeginTransactionResult,
ActionCancelQueryRequest, ActionCancelQueryResult,
ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
ActionCreatePreparedStatementResult, ActionCreatePreparedSubstraitPlanRequest,
ActionEndSavepointRequest, ActionEndTransactionRequest, CommandGetCatalogs,
CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys,
CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo,
CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo,
CommandPreparedStatementQuery, CommandPreparedStatementUpdate, CommandStatementQuery,
CommandStatementSubstraitPlan, CommandStatementUpdate, SqlInfo, TicketStatementQuery,
};
use arrow_flight::{
Action, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo, HandshakeRequest,
HandshakeResponse, Location, Ticket,
};
use base64::Engine;
use futures::Stream;
use log::{debug, error, warn};
use std::convert::TryFrom;
use std::pin::Pin;
use std::str::FromStr;
use std::string::ToString;
use std::sync::Arc;
use std::time::Duration;
use tonic::{Request, Response, Status, Streaming};
use crate::scheduler_server::SchedulerServer;
use arrow_flight::flight_service_client::FlightServiceClient;
use arrow_flight::sql::ProstMessageExt;
use arrow_flight::utils::batches_to_flight_data;
use arrow_flight::SchemaAsIpc;
use ballista_core::config::BallistaConfig;
use ballista_core::serde::protobuf;
use ballista_core::serde::protobuf::action::ActionType::FetchPartition;
use ballista_core::serde::protobuf::job_status;
use ballista_core::serde::protobuf::JobStatus;
use ballista_core::serde::protobuf::SuccessfulJob;
use ballista_core::utils::create_grpc_client_connection;
use dashmap::DashMap;
use datafusion::arrow;
use datafusion::arrow::array::{ArrayRef, StringArray};
use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion::arrow::error::ArrowError;
use datafusion::arrow::ipc::writer::{IpcDataGenerator, IpcWriteOptions};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::DFSchemaRef;
use datafusion::logical_expr::LogicalPlan;
use datafusion::prelude::SessionContext;
use datafusion_proto::protobuf::{LogicalPlanNode, PhysicalPlanNode};
use prost::Message;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::time::sleep;
use tokio_stream::wrappers::ReceiverStream;
use tonic::metadata::MetadataValue;
use uuid::Uuid;
pub struct FlightSqlServiceImpl {
server: SchedulerServer<LogicalPlanNode, PhysicalPlanNode>,
statements: Arc<DashMap<Uuid, LogicalPlan>>,
contexts: Arc<DashMap<Uuid, Arc<SessionContext>>>,
}
const TABLE_TYPES: [&str; 2] = ["TABLE", "VIEW"];
impl FlightSqlServiceImpl {
pub fn new(server: SchedulerServer<LogicalPlanNode, PhysicalPlanNode>) -> Self {
Self {
server,
statements: Default::default(),
contexts: Default::default(),
}
}
#[allow(deprecated)]
fn tables(&self, ctx: Arc<SessionContext>) -> Result<RecordBatch, ArrowError> {
let schema = Arc::new(Schema::new(vec![
Field::new("catalog_name", DataType::Utf8, true),
Field::new("db_schema_name", DataType::Utf8, true),
Field::new("table_name", DataType::Utf8, false),
Field::new("table_type", DataType::Utf8, false),
]));
let tables = ctx.tables()?; // resolved in #501
let names: Vec<_> = tables.iter().map(|it| Some(it.as_str())).collect();
let types: Vec<_> = names.iter().map(|_| Some("TABLE")).collect();
let cats: Vec<_> = names.iter().map(|_| None).collect();
let schemas: Vec<_> = names.iter().map(|_| None).collect();
let rb = RecordBatch::try_new(
schema,
[cats, schemas, names, types]
.iter()
.map(|i| Arc::new(StringArray::from(i.clone())) as ArrayRef)
.collect::<Vec<_>>(),
)?;
Ok(rb)
}
fn table_types() -> Result<RecordBatch, ArrowError> {
let schema = Arc::new(Schema::new(vec![Field::new(
"table_type",
DataType::Utf8,
false,
)]));
RecordBatch::try_new(
schema,
[TABLE_TYPES]
.iter()
.map(|i| Arc::new(StringArray::from(i.to_vec())) as ArrayRef)
.collect::<Vec<_>>(),
)
}
async fn create_ctx(&self) -> Result<Uuid, Status> {
let config_builder = BallistaConfig::builder();
let config = config_builder
.build()
.map_err(|e| Status::internal(format!("Error building config: {e}")))?;
let ctx = self
.server
.state
.session_manager
.create_session(&config)
.await
.map_err(|e| {
Status::internal(format!("Failed to create SessionContext: {e:?}"))
})?;
let handle = Uuid::new_v4();
self.contexts.insert(handle, ctx);
Ok(handle)
}
fn get_ctx<T>(&self, req: &Request<T>) -> Result<Arc<SessionContext>, Status> {
let auth = req
.metadata()
.get("authorization")
.ok_or_else(|| Status::internal("No authorization header!"))?;
let str = auth
.to_str()
.map_err(|e| Status::internal(format!("Error parsing header: {e}")))?;
let authorization = str.to_string();
let bearer = "Bearer ";
if !authorization.starts_with(bearer) {
Err(Status::internal("Invalid auth header!"))?;
}
let auth = authorization[bearer.len()..].to_string();
let handle = Uuid::from_str(auth.as_str())
.map_err(|e| Status::internal(format!("Error locking contexts: {e}")))?;
if let Some(context) = self.contexts.get(&handle) {
Ok(context.clone())
} else {
Err(Status::internal(format!(
"Context handle not found: {handle}"
)))?
}
}
async fn prepare_statement(
query: &str,
ctx: &Arc<SessionContext>,
) -> Result<LogicalPlan, Status> {
let plan = ctx
.sql(query)
.await
.and_then(|df| df.into_optimized_plan())
.map_err(|e| Status::internal(format!("Error building plan: {e}")))?;
Ok(plan)
}
async fn check_job(&self, job_id: &String) -> Result<Option<SuccessfulJob>, Status> {
let status = self
.server
.state
.task_manager
.get_job_status(job_id)
.await
.map_err(|e| {
let msg = format!("Error getting status for job {job_id}: {e:?}");
error!("{}", msg);
Status::internal(msg)
})?;
let status: JobStatus = match status {
Some(status) => status,
None => {
let msg = format!("Error getting status for job {job_id}!");
error!("{}", msg);
Err(Status::internal(msg))?
}
};
let status: job_status::Status = match status.status {
Some(status) => status,
None => {
let msg = format!("Error getting status for job {job_id}!");
error!("{}", msg);
Err(Status::internal(msg))?
}
};
match status {
job_status::Status::Queued(_) => Ok(None),
job_status::Status::Running(_) => Ok(None),
job_status::Status::Failed(e) => {
warn!("Error executing plan: {:?}", e);
Err(Status::internal(format!(
"Error executing plan: {}",
e.error
)))?
}
job_status::Status::Successful(comp) => Ok(Some(comp)),
}
}
async fn job_to_fetch_part(
&self,
completed: SuccessfulJob,
num_rows: &mut i64,
num_bytes: &mut i64,
) -> Result<Vec<FlightEndpoint>, Status> {
let mut fieps: Vec<_> = vec![];
for loc in completed.partition_location.iter() {
let (exec_host, exec_port) = if let Some(ref md) = loc.executor_meta {
(md.host.clone(), md.port)
} else {
Err(Status::internal(
"Invalid partition location, missing executor metadata and advertise_endpoint flag is undefined.".to_string(),
))?
};
let (host, port) = match &self
.server
.state
.config
.advertise_flight_sql_endpoint
{
Some(endpoint) => {
let advertise_endpoint_vec: Vec<&str> = endpoint.split(':').collect();
match advertise_endpoint_vec.as_slice() {
[host_ip, port] => {
(String::from(*host_ip), FromStr::from_str(port).expect("Failed to parse port from advertise-endpoint."))
}
_ => {
Err(Status::internal("advertise-endpoint flag has incorrect format. Expected IP:Port".to_string()))?
}
}
}
None => (exec_host.clone(), exec_port),
};
let fetch = if let Some(ref id) = loc.partition_id {
let fetch = protobuf::FetchPartition {
job_id: id.job_id.clone(),
stage_id: id.stage_id,
partition_id: id.partition_id,
path: loc.path.clone(),
// Use executor ip:port for routing to flight result
host: exec_host.clone(),
port: exec_port,
};
protobuf::Action {
action_type: Some(FetchPartition(fetch)),
settings: vec![],
}
} else {
Err(Status::internal("Error getting partition ID".to_string()))?
};
if let Some(ref stats) = loc.partition_stats {
*num_rows += stats.num_rows;
*num_bytes += stats.num_bytes;
} else {
Err(Status::internal("Error getting stats".to_string()))?
}
let authority = format!("{}:{}", &host, &port);
let loc = Location {
uri: format!("grpc+tcp://{authority}"),
};
let buf = fetch.as_any().encode_to_vec();
let ticket = Ticket { ticket: buf.into() };
let fiep = FlightEndpoint {
ticket: Some(ticket),
location: vec![loc],
};
fieps.push(fiep);
}
Ok(fieps)
}
fn make_local_fieps(&self, job_id: &str) -> Result<Vec<FlightEndpoint>, Status> {
let (host, port) = ("127.0.0.1".to_string(), 50050); // TODO: use advertise host
let fetch = protobuf::FetchPartition {
job_id: job_id.to_string(),
stage_id: 0,
partition_id: 0,
path: job_id.to_string(),
host: host.clone(),
port,
};
let fetch = protobuf::Action {
action_type: Some(FetchPartition(fetch)),
settings: vec![],
};
let authority = format!("{}:{}", &host, &port); // TODO: use advertise host
let loc = Location {
uri: format!("grpc+tcp://{authority}"),
};
let buf = fetch.as_any().encode_to_vec();
let ticket = Ticket { ticket: buf.into() };
let fiep = FlightEndpoint {
ticket: Some(ticket),
location: vec![loc],
};
let fieps = vec![fiep];
Ok(fieps)
}
fn cache_plan(&self, plan: LogicalPlan) -> Result<Uuid, Status> {
let handle = Uuid::new_v4();
self.statements.insert(handle, plan);
Ok(handle)
}
fn get_plan(&self, handle: &Uuid) -> Result<LogicalPlan, Status> {
if let Some(plan) = self.statements.get(handle) {
Ok(plan.clone())
} else {
Err(Status::internal(format!(
"Statement handle not found: {handle}"
)))?
}
}
fn remove_plan(&self, handle: Uuid) -> Result<(), Status> {
self.statements.remove(&handle);
Ok(())
}
fn df_schema_to_arrow(&self, schema: &DFSchemaRef) -> Result<Vec<u8>, Status> {
let arrow_schema: Schema = (&**schema).into();
let schema_bytes = self.schema_to_arrow(Arc::new(arrow_schema))?;
Ok(schema_bytes)
}
fn schema_to_arrow(&self, arrow_schema: SchemaRef) -> Result<Vec<u8>, Status> {
let options = IpcWriteOptions::default();
let pair = SchemaAsIpc::new(&arrow_schema, &options);
let data_gen = IpcDataGenerator::default();
let encoded_data = data_gen.schema_to_bytes(pair.0, pair.1);
let mut schema_bytes = vec![];
arrow::ipc::writer::write_message(&mut schema_bytes, encoded_data, pair.1)
.map_err(|e| Status::internal(format!("Error encoding schema: {e}")))?;
Ok(schema_bytes)
}
async fn enqueue_job(
&self,
ctx: Arc<SessionContext>,
plan: &LogicalPlan,
) -> Result<String, Status> {
let job_id = self.server.state.task_manager.generate_job_id();
let job_name = format!("Flight SQL job {job_id}");
self.server
.submit_job(&job_id, &job_name, ctx, plan)
.await
.map_err(|e| {
let msg = format!("Failed to send JobQueued event for {job_id}: {e:?}");
error!("{}", msg);
Status::internal(msg)
})?;
Ok(job_id)
}
fn create_resp(
schema_bytes: Vec<u8>,
fieps: Vec<FlightEndpoint>,
num_rows: i64,
num_bytes: i64,
) -> Response<FlightInfo> {
let flight_desc = FlightDescriptor {
r#type: DescriptorType::Cmd.into(),
cmd: Vec::new().into(),
path: vec![],
};
let info = FlightInfo {
schema: schema_bytes.into(),
flight_descriptor: Some(flight_desc),
endpoint: fieps,
total_records: num_rows,
total_bytes: num_bytes,
ordered: false,
};
Response::new(info)
}
async fn execute_plan(
&self,
ctx: Arc<SessionContext>,
plan: &LogicalPlan,
) -> Result<Response<FlightInfo>, Status> {
let job_id = self.enqueue_job(ctx, plan).await?;
// poll for job completion
let mut num_rows = 0;
let mut num_bytes = 0;
let fieps = loop {
sleep(Duration::from_millis(100)).await;
let completed = if let Some(comp) = self.check_job(&job_id).await? {
comp
} else {
continue;
};
let fieps = self
.job_to_fetch_part(completed, &mut num_rows, &mut num_bytes)
.await?;
break fieps;
};
// Generate response
let schema_bytes = self.df_schema_to_arrow(plan.schema())?;
let resp = Self::create_resp(schema_bytes, fieps, num_rows, num_bytes);
Ok(resp)
}
async fn record_batch_to_resp(
rb: RecordBatch,
) -> Result<
Response<Pin<Box<dyn Stream<Item = Result<FlightData, Status>> + Send>>>,
Status,
> {
type FlightResult = Result<FlightData, Status>;
let (tx, rx): (Sender<FlightResult>, Receiver<FlightResult>) = channel(2);
let schema = rb.schema();
let flights = batches_to_flight_data(&schema, vec![rb])
.map_err(|_| Status::internal("Error encoding batches".to_string()))?;
for flight in flights {
tx.send(Ok(flight))
.await
.map_err(|_| Status::internal("Error sending flight".to_string()))?;
}
let resp = Response::new(Box::pin(ReceiverStream::new(rx))
as Pin<Box<dyn Stream<Item = Result<FlightData, Status>> + Send + 'static>>);
Ok(resp)
}
fn batch_to_schema_resp(
&self,
data: &RecordBatch,
name: &str,
) -> Result<Response<FlightInfo>, Status> {
let num_bytes = data.get_array_memory_size() as i64;
let schema = data.schema();
let num_rows = data.num_rows() as i64;
let fieps = self.make_local_fieps(name)?;
let schema_bytes = self.schema_to_arrow(schema)?;
let resp = Self::create_resp(schema_bytes, fieps, num_rows, num_bytes);
Ok(resp)
}
}
#[tonic::async_trait]
impl FlightSqlService for FlightSqlServiceImpl {
type FlightService = FlightSqlServiceImpl;
async fn do_handshake(
&self,
request: Request<Streaming<HandshakeRequest>>,
) -> Result<
Response<Pin<Box<dyn Stream<Item = Result<HandshakeResponse, Status>> + Send>>>,
Status,
> {
debug!("do_handshake");
for md in request.metadata().iter() {
debug!("{:?}", md);
}
let basic = "Basic ";
let authorization = request
.metadata()
.get("authorization")
.ok_or_else(|| Status::invalid_argument("authorization field not present"))?
.to_str()
.map_err(|_| Status::invalid_argument("authorization not parsable"))?;
if !authorization.starts_with(basic) {
Err(Status::invalid_argument(format!(
"Auth type not implemented: {authorization}"
)))?;
}
let bytes = base64::engine::general_purpose::STANDARD
.decode(&authorization[basic.len()..])
.map_err(|_| Status::invalid_argument("authorization not parsable"))?;
let str = String::from_utf8(bytes)
.map_err(|_| Status::invalid_argument("authorization not parsable"))?;
let parts: Vec<_> = str.split(':').collect();
if parts.len() != 2 {
Err(Status::invalid_argument("Invalid authorization header"))?;
}
let user = parts[0];
let pass = parts[1];
if user != "admin" || pass != "password" {
Err(Status::unauthenticated("Invalid credentials!"))?
}
let token = self.create_ctx().await?;
let result = HandshakeResponse {
protocol_version: 0,
payload: token.as_bytes().to_vec().into(),
};
let result = Ok(result);
let output = futures::stream::iter(vec![result]);
let str = format!("Bearer {token}");
let mut resp: Response<Pin<Box<dyn Stream<Item = Result<_, _>> + Send>>> =
Response::new(Box::pin(output));
let md = MetadataValue::try_from(str)
.map_err(|_| Status::invalid_argument("authorization not parsable"))?;
resp.metadata_mut().insert("authorization", md);
Ok(resp)
}
async fn do_get_fallback(
&self,
request: Request<Ticket>,
message: arrow_flight::sql::Any,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_fallback type_url: {}", message.type_url);
let ctx = self.get_ctx(&request)?;
if !message.is::<protobuf::Action>() {
Err(Status::unimplemented(format!(
"do_get: The defined request is invalid: {}",
message.type_url
)))?
}
let action: protobuf::Action = message
.unpack()
.map_err(|e| Status::internal(format!("{e:?}")))?
.ok_or_else(|| Status::internal("Expected an Action but got None!"))?;
let fp = match &action.action_type {
Some(FetchPartition(fp)) => fp.clone(),
None => Err(Status::internal("Expected an ActionType but got None!"))?,
};
// Well-known job ID: respond with the data
match fp.job_id.as_str() {
"get_flight_info_table_types" => {
debug!("Responding with table types");
let rb = FlightSqlServiceImpl::table_types().map_err(|_| {
Status::internal("Error getting table types".to_string())
})?;
let resp = Self::record_batch_to_resp(rb).await?;
return Ok(resp);
}
"get_flight_info_tables" => {
debug!("Responding with tables");
let rb = self
.tables(ctx)
.map_err(|_| Status::internal("Error getting tables".to_string()))?;
let resp = Self::record_batch_to_resp(rb).await?;
return Ok(resp);
}
_ => {}
}
// Proxy the flight
let addr = format!("http://{}:{}", fp.host, fp.port);
debug!("Scheduler proxying flight for to {}", addr);
let connection =
create_grpc_client_connection(addr.clone())
.await
.map_err(|e| {
Status::internal(format!(
"Error connecting to Ballista scheduler or executor at {addr}: {e:?}"
))
})?;
let mut flight_client = FlightServiceClient::new(connection);
let buf = action.encode_to_vec();
let request = Request::new(Ticket { ticket: buf.into() });
let stream = flight_client
.do_get(request)
.await
.map_err(|e| Status::internal(format!("{e:?}")))?
.into_inner();
Ok(Response::new(Box::pin(stream)))
}
/// Get a FlightDataStream containing the data related to the supported XDBC types.
async fn do_get_xdbc_type_info(
&self,
_query: CommandGetXdbcTypeInfo,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_xdbc_type_info");
Err(Status::unimplemented("Implement do_get_xdbc_type_info"))
}
async fn get_flight_info_statement(
&self,
query: CommandStatementQuery,
request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_statement query:\n{}", query.query);
let ctx = self.get_ctx(&request)?;
let plan = Self::prepare_statement(&query.query, &ctx).await?;
let resp = self.execute_plan(ctx, &plan).await?;
debug!("Returning flight info...");
Ok(resp)
}
async fn get_flight_info_prepared_statement(
&self,
handle: CommandPreparedStatementQuery,
request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_prepared_statement");
let ctx = self.get_ctx(&request)?;
let handle = Uuid::from_slice(handle.prepared_statement_handle.as_ref())
.map_err(|e| Status::internal(format!("Error decoding handle: {e}")))?;
let plan = self.get_plan(&handle)?;
let resp = self.execute_plan(ctx, &plan).await?;
debug!("Responding to query {}...", handle);
Ok(resp)
}
async fn get_flight_info_catalogs(
&self,
_query: CommandGetCatalogs,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_catalogs");
Err(Status::unimplemented("Implement get_flight_info_catalogs"))
}
async fn get_flight_info_schemas(
&self,
_query: CommandGetDbSchemas,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_schemas");
Err(Status::unimplemented("Implement get_flight_info_schemas"))
}
async fn get_flight_info_tables(
&self,
_query: CommandGetTables,
request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_tables");
let ctx = self.get_ctx(&request)?;
let data = self
.tables(ctx)
.map_err(|e| Status::internal(format!("Error getting tables: {e}")))?;
let resp = self.batch_to_schema_resp(&data, "get_flight_info_tables")?;
Ok(resp)
}
async fn get_flight_info_table_types(
&self,
_query: CommandGetTableTypes,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_table_types");
let data = FlightSqlServiceImpl::table_types()
.map_err(|e| Status::internal(format!("Error getting table types: {e}")))?;
let resp = self.batch_to_schema_resp(&data, "get_flight_info_table_types")?;
Ok(resp)
}
async fn get_flight_info_sql_info(
&self,
_query: CommandGetSqlInfo,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_sql_info");
// TODO: implement for FlightSQL JDBC to work
Err(Status::unimplemented("Implement CommandGetSqlInfo"))
}
async fn get_flight_info_primary_keys(
&self,
_query: CommandGetPrimaryKeys,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_primary_keys");
Err(Status::unimplemented(
"Implement get_flight_info_primary_keys",
))
}
async fn get_flight_info_exported_keys(
&self,
_query: CommandGetExportedKeys,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_exported_keys");
Err(Status::unimplemented(
"Implement get_flight_info_exported_keys",
))
}
async fn get_flight_info_imported_keys(
&self,
_query: CommandGetImportedKeys,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_imported_keys");
Err(Status::unimplemented(
"Implement get_flight_info_imported_keys",
))
}
async fn get_flight_info_cross_reference(
&self,
_query: CommandGetCrossReference,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_cross_reference");
Err(Status::unimplemented(
"Implement get_flight_info_cross_reference",
))
}
/// Get a FlightInfo to extract information about the supported XDBC types.
async fn get_flight_info_xdbc_type_info(
&self,
_query: CommandGetXdbcTypeInfo,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_xdbc_type_info");
Err(Status::unimplemented(
"Implement get_flight_info_xdbc_type_info",
))
}
async fn do_get_statement(
&self,
_ticket: TicketStatementQuery,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_statement");
// let handle = Uuid::from_slice(&ticket.statement_handle)
// .map_err(|e| Status::internal(format!("Error decoding ticket: {}", e)))?;
// let statements = self.statements.try_lock()
// .map_err(|e| Status::internal(format!("Error decoding ticket: {}", e)))?;
// let plan = statements.get(&handle);
Err(Status::unimplemented("Implement do_get_statement"))
}
async fn do_get_prepared_statement(
&self,
_query: CommandPreparedStatementQuery,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_prepared_statement");
Err(Status::unimplemented("Implement do_get_prepared_statement"))
}
async fn do_get_catalogs(
&self,
_query: CommandGetCatalogs,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_catalogs");
Err(Status::unimplemented("Implement do_get_catalogs"))
}
async fn do_get_schemas(
&self,
_query: CommandGetDbSchemas,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_schemas");
Err(Status::unimplemented("Implement do_get_schemas"))
}
async fn do_get_tables(
&self,
_query: CommandGetTables,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_tables");
Err(Status::unimplemented("Implement do_get_tables"))
}
async fn do_get_table_types(
&self,
_query: CommandGetTableTypes,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_table_types");
Err(Status::unimplemented("Implement do_get_table_types"))
}
async fn do_get_sql_info(
&self,
_query: CommandGetSqlInfo,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_sql_info");
Err(Status::unimplemented("Implement do_get_sql_info"))
}
async fn do_get_primary_keys(
&self,
_query: CommandGetPrimaryKeys,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_primary_keys");
Err(Status::unimplemented("Implement do_get_primary_keys"))
}
async fn do_get_exported_keys(
&self,
_query: CommandGetExportedKeys,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_exported_keys");
Err(Status::unimplemented("Implement do_get_exported_keys"))
}
async fn do_get_imported_keys(
&self,
_query: CommandGetImportedKeys,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_imported_keys");
Err(Status::unimplemented("Implement do_get_imported_keys"))
}
async fn do_get_cross_reference(
&self,
_query: CommandGetCrossReference,
_request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
debug!("do_get_cross_reference");
Err(Status::unimplemented("Implement do_get_cross_reference"))
}
// do_put
async fn do_put_statement_update(
&self,
_ticket: CommandStatementUpdate,
_request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
debug!("do_put_statement_update");
Err(Status::unimplemented("Implement do_put_statement_update"))
}
async fn do_put_prepared_statement_query(
&self,
_query: CommandPreparedStatementQuery,
_request: Request<PeekableFlightDataStream>,
) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
debug!("do_put_prepared_statement_query");
Err(Status::unimplemented(
"Implement do_put_prepared_statement_query",
))
}
async fn do_put_prepared_statement_update(
&self,
handle: CommandPreparedStatementUpdate,
request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
debug!("do_put_prepared_statement_update");
let ctx = self.get_ctx(&request)?;
let handle = Uuid::from_slice(handle.prepared_statement_handle.as_ref())
.map_err(|e| Status::internal(format!("Error decoding handle: {e}")))?;
let plan = self.get_plan(&handle)?;
let _ = self.execute_plan(ctx, &plan).await?;
debug!("Sending -1 rows affected");
Ok(-1)
}
async fn do_action_create_prepared_statement(
&self,
query: ActionCreatePreparedStatementRequest,
request: Request<Action>,
) -> Result<ActionCreatePreparedStatementResult, Status> {
debug!("do_action_create_prepared_statement");
let ctx = self.get_ctx(&request)?;
let plan = Self::prepare_statement(&query.query, &ctx).await?;
let schema_bytes = self.df_schema_to_arrow(plan.schema())?;
let handle = self.cache_plan(plan)?;
debug!("Prepared statement {}:\n{}", handle, query.query);
let res = ActionCreatePreparedStatementResult {
prepared_statement_handle: handle.as_bytes().to_vec().into(),
dataset_schema: schema_bytes.into(),
parameter_schema: Vec::new().into(), // TODO: parameters
};
Ok(res)
}
async fn do_action_close_prepared_statement(
&self,
handle: ActionClosePreparedStatementRequest,
_request: Request<Action>,
) -> Result<(), Status> {
debug!("do_action_close_prepared_statement");
let handle = Uuid::from_slice(handle.prepared_statement_handle.as_ref())
.map(|id| {
debug!("Closing {}", id);
id
})
.map_err(|e| Status::internal(format!("Failed to parse handle: {e:?}")))?;
self.remove_plan(handle)
}
/// Get a FlightInfo for executing a substrait plan.
async fn get_flight_info_substrait_plan(
&self,
_query: CommandStatementSubstraitPlan,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
debug!("get_flight_info_substrait_plan");
Err(Status::unimplemented(
"Implement get_flight_info_substrait_plan",
))
}
/// Execute a substrait plan
async fn do_put_substrait_plan(
&self,
_query: CommandStatementSubstraitPlan,
_request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
debug!("do_put_substrait_plan");
Err(Status::unimplemented("Implement do_put_substrait_plan"))
}
/// Create a prepared substrait plan.
async fn do_action_create_prepared_substrait_plan(
&self,
_query: ActionCreatePreparedSubstraitPlanRequest,
_request: Request<Action>,
) -> Result<ActionCreatePreparedStatementResult, Status> {
debug!("do_action_create_prepared_substrait_plan");
Err(Status::unimplemented(
"Implement do_action_create_prepared_substrait_plan",
))
}
/// Begin a transaction
async fn do_action_begin_transaction(
&self,
_query: ActionBeginTransactionRequest,
_request: Request<Action>,
) -> Result<ActionBeginTransactionResult, Status> {
debug!("do_action_begin_transaction");
Err(Status::unimplemented(
"Implement do_action_begin_transaction",
))
}
/// End a transaction
async fn do_action_end_transaction(
&self,
_query: ActionEndTransactionRequest,
_request: Request<Action>,
) -> Result<(), Status> {
debug!("do_action_end_transaction");
Err(Status::unimplemented("Implement do_action_end_transaction"))
}
/// Begin a savepoint
async fn do_action_begin_savepoint(
&self,
_query: ActionBeginSavepointRequest,
_request: Request<Action>,
) -> Result<ActionBeginSavepointResult, Status> {
debug!("do_action_begin_savepoint");
Err(Status::unimplemented("Implement do_action_begin_savepoint"))
}
/// End a savepoint
async fn do_action_end_savepoint(
&self,
_query: ActionEndSavepointRequest,
_request: Request<Action>,
) -> Result<(), Status> {
debug!("do_action_end_savepoint");
Err(Status::unimplemented("Implement do_action_end_savepoint"))
}
/// Cancel a query
async fn do_action_cancel_query(
&self,
_query: ActionCancelQueryRequest,
_request: Request<Action>,
) -> Result<ActionCancelQueryResult, Status> {
debug!("do_action_cancel_query");
Err(Status::unimplemented("Implement do_action_cancel_query"))
}