-
Notifications
You must be signed in to change notification settings - Fork 36
/
mod.rs
1423 lines (1289 loc) · 47.5 KB
/
mod.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
pub mod errors;
mod query_exec;
mod tls;
use crate::common::ssh::session::SshTunnelSession;
use crate::common::ssh::{key::SshKey, session::SshTunnelAccess};
use crate::common::util::{self, create_count_record_batch};
use async_trait::async_trait;
use chrono::naive::{NaiveDateTime, NaiveTime};
use chrono::{DateTime, NaiveDate, Timelike, Utc};
use datafusion::arrow::array::Decimal128Builder;
use datafusion::arrow::datatypes::{
DataType, Field, Fields, Schema as ArrowSchema, SchemaRef as ArrowSchemaRef, TimeUnit,
};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::datasource::TableProvider;
use datafusion::error::{DataFusionError, Result as DatafusionResult};
use datafusion::execution::context::SessionState;
use datafusion::execution::context::TaskContext;
use datafusion::logical_expr::{Expr, TableProviderFilterPushDown, TableType};
use datafusion::physical_expr::PhysicalSortExpr;
use datafusion::physical_plan::memory::MemoryExec;
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion::physical_plan::metrics::MetricsSet;
use datafusion::physical_plan::{
execute_stream, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, RecordBatchStream,
SendableRecordBatchStream, Statistics,
};
use datafusion::scalar::ScalarValue;
use datafusion_ext::errors::ExtensionError;
use datafusion_ext::functions::VirtualLister;
use datafusion_ext::metrics::DataSourceMetricsStreamAdapter;
use errors::{PostgresError, Result};
use futures::{future::BoxFuture, ready, stream::BoxStream, FutureExt, Stream, StreamExt};
use protogen::metastore::types::options::TunnelOptions;
use protogen::{FromOptionalField, ProtoConvError};
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::borrow::{Borrow, Cow};
use std::fmt::{self, Write};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio::task::JoinHandle;
use tokio_postgres::binary_copy::{BinaryCopyOutRow, BinaryCopyOutStream};
use tokio_postgres::config::{Host, SslMode};
use tokio_postgres::tls::MakeTlsConnect;
use tokio_postgres::types::{FromSql, Type as PostgresType};
use tokio_postgres::{Client, Config, Connection, CopyOutStream, NoTls, Socket};
use tracing::{debug, warn};
use self::query_exec::PostgresQueryExec;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PostgresDbConnection {
ConnectionString(String),
Parameters {
host: String,
port: Option<u16>,
user: String,
password: Option<String>,
database: String,
},
}
impl PostgresDbConnection {
pub fn connection_string(&self) -> String {
match self {
Self::ConnectionString(s) => s.to_owned(),
Self::Parameters {
host,
port,
user,
password,
database,
} => {
let mut conn_str = String::from("postgres://");
// Credentials
write!(&mut conn_str, "{user}").unwrap();
if let Some(password) = password {
write!(&mut conn_str, ":{password}").unwrap();
}
// Address
write!(&mut conn_str, "@{host}").unwrap();
if let Some(port) = port {
write!(&mut conn_str, ":{port}").unwrap();
}
// Database
write!(&mut conn_str, "/{database}").unwrap();
conn_str
}
}
}
}
/// Information needed for create a postgres client.
#[derive(Debug, Clone)]
pub struct PostgresAccess {
/// Connection string to the postgres instance.
pub conn_str: PostgresDbConnection,
/// Tunnel to use to access instance.
pub tunnel: Option<TunnelOptions>,
}
impl PostgresAccess {
pub fn new_from_conn_str(
conn_str: impl Into<String>,
tunnel: Option<TunnelOptions>,
) -> PostgresAccess {
PostgresAccess {
conn_str: PostgresDbConnection::ConnectionString(conn_str.into()),
tunnel,
}
}
/// Connect to an instance using these connection details.
pub async fn connect(&self) -> Result<PostgresAccessState> {
let state =
PostgresAccessState::connect(&self.conn_str.connection_string(), self.tunnel.clone())
.await?;
Ok(state)
}
/// Validates access to the postgres instance.
pub async fn validate_access(&self) -> Result<()> {
let state = self.connect().await?;
state.client.execute("SELECT 1", &[]).await?;
Ok(())
}
/// Validates access to a single table.
pub async fn validate_table_access(&self, schema: &str, table: &str) -> Result<()> {
let state = self.connect().await?;
let query = format!("SELECT * FROM {}.{} where false", schema, table);
state.client.execute(query.as_str(), &[]).await?;
Ok(())
}
}
impl TryFrom<protogen::sqlexec::common::PostgresAccess> for PostgresAccess {
type Error = ProtoConvError;
fn try_from(
value: protogen::sqlexec::common::PostgresAccess,
) -> std::result::Result<Self, Self::Error> {
Ok(Self::new_from_conn_str(
value.conn_str,
value.tunnel.map(|t| t.try_into()).transpose()?,
))
}
}
impl From<PostgresAccess> for protogen::sqlexec::common::PostgresAccess {
fn from(value: PostgresAccess) -> Self {
Self {
conn_str: value.conn_str.connection_string(),
tunnel: value.tunnel.map(|t| t.into()),
}
}
}
#[derive(Debug)]
pub struct PostgresAccessState {
/// The Postgres client.
client: tokio_postgres::Client,
/// Handle for the underlying Postgres connection.
/// Also contains the `Session` for the underlying ssh tunnel
///
/// Kept on struct to avoid dropping the postgres connection future and ssh tunnel.
#[allow(dead_code)]
conn_handle: JoinHandle<()>,
}
impl PostgresAccessState {
/// Connect to a postgres instance.
async fn connect(connection_string: &str, tunnel: Option<TunnelOptions>) -> Result<Self> {
let (client, conn_handle) = Self::connect_internal(connection_string, tunnel).await?;
Ok(PostgresAccessState {
client,
conn_handle,
})
}
async fn connect_internal(
connection_string: &str,
tunnel: Option<TunnelOptions>,
) -> Result<(Client, JoinHandle<()>)> {
match tunnel {
None => Self::connect_direct(connection_string).await,
Some(TunnelOptions::Ssh(ssh_options)) => {
let keypair = SshKey::from_bytes(&ssh_options.ssh_key)?;
let tunnel_access = SshTunnelAccess {
connection_string: ssh_options.connection_string,
keypair,
};
Self::connect_with_ssh_tunnel(connection_string, &tunnel_access).await
}
Some(opt) => Err(PostgresError::UnsupportedTunnel(opt.to_string())),
}
}
async fn connect_direct(connection_string: &str) -> Result<(Client, JoinHandle<()>)> {
let config: Config = connection_string.parse()?;
fn spawn_conn<T: AsyncRead + AsyncWrite + Send + Unpin + 'static>(
conn: Connection<Socket, T>,
) -> JoinHandle<()> {
tokio::spawn(async move {
if let Err(e) = conn.await {
warn!(%e, "postgres connection errored");
}
})
}
// Configure tls depending on ssl mode.
//
// - Disable => no tls
// - Prefer => try tls, fallback to no tls on connection error
// - Require => try tls, no fallback
// - Any other => return unsupported
let (client, handle) = match config.get_ssl_mode() {
SslMode::Disable => {
let (client, conn) = tokio_postgres::connect(connection_string, NoTls).await?;
let handle = spawn_conn(conn);
(client, handle)
}
SslMode::Prefer => {
match tokio_postgres::connect(connection_string, tls::MakeRustlsConnect::default())
.await
{
Ok((client, conn)) => {
let handle = spawn_conn(conn);
(client, handle)
}
Err(e) => {
// The tokio postgres lib does discriminate between tls
// and other errors, but that's not made public.
debug!(%e, "pg conn falling back to no tls");
let (client, conn) =
tokio_postgres::connect(connection_string, NoTls).await?;
let handle = spawn_conn(conn);
(client, handle)
}
}
}
SslMode::Require => {
let (client, conn) =
tokio_postgres::connect(connection_string, tls::MakeRustlsConnect::default())
.await?;
let handle = spawn_conn(conn);
(client, handle)
}
other => return Err(PostgresError::UnsupportSslMode(other)),
};
Ok((client, handle))
}
async fn connect_with_ssh_tunnel(
connection_string: &str,
ssh_tunnel: &SshTunnelAccess,
) -> Result<(Client, JoinHandle<()>)> {
let config: Config = connection_string.parse()?;
let postgres_host = config
.get_hosts()
.iter()
.find_map(|host| match host {
Host::Tcp(host) => Some(host.clone()),
_ => None,
})
.ok_or(PostgresError::InvalidPgHosts(config.get_hosts().to_vec()))?;
let postgres_port = config.get_ports().iter().next().cloned().unwrap_or(5432);
// Open ssh tunnel
let (session, tunnel_addr) = ssh_tunnel
.create_tunnel(&(postgres_host, postgres_port))
.await?;
fn spawn_conn<T: AsyncRead + AsyncWrite + Send + Unpin + 'static>(
conn: Connection<TcpStream, T>,
session: SshTunnelSession,
) -> JoinHandle<()> {
tokio::spawn(async move {
if let Err(e) = conn.await {
warn!(%e, "postgres connection errored");
}
// If postgres connection is complete, close ssh tunnel
if let Err(e) = session.close().await {
warn!(%e, "closing ssh tunnel errored");
}
})
}
let tcp_stream = TcpStream::connect(tunnel_addr).await?;
// Rust doesn't feel like type inferring this for us.
let tls_connect = <tls::MakeRustlsConnect as MakeTlsConnect<TcpStream>>::make_tls_connect(
&mut tls::MakeRustlsConnect::default(),
// TODO: Which host do we want to specify? Since this is being tunneled
// over ssh, I don't know if SNI actually matters.
"",
)?;
// Configure tls depending on ssl mode.
//
// - Disable => no tls
// - Prefer => try tls, fallback to no tls on connection error
// - Require => try tls, no fallback
// - Any other => return unsupported
let (client, handle) = match config.get_ssl_mode() {
SslMode::Disable => {
let (client, conn) = config.connect_raw(tcp_stream, NoTls).await?;
let handle = spawn_conn(conn, session);
(client, handle)
}
SslMode::Prefer => {
match config.connect_raw(tcp_stream, tls_connect).await {
Ok((client, conn)) => {
let handle = spawn_conn(conn, session);
(client, handle)
}
Err(e) => {
// The tokio postgres lib does discriminate between tls
// and other errors, but that's not made public.
debug!(%e, "pg conn falling back to no tls");
// Reconnect to get a fresh stream.
let tcp_stream = TcpStream::connect(tunnel_addr).await?;
let (client, conn) = config.connect_raw(tcp_stream, NoTls).await?;
let handle = spawn_conn(conn, session);
(client, handle)
}
}
}
SslMode::Require => {
let (client, conn) = config.connect_raw(tcp_stream, tls_connect).await?;
let handle = spawn_conn(conn, session);
(client, handle)
}
other => return Err(PostgresError::UnsupportSslMode(other)),
};
Ok((client, handle))
}
async fn get_table_schema(
&self,
schema: &str,
name: &str,
) -> Result<(ArrowSchema, Vec<PostgresType>)> {
// TODO: Get schema using `information_schema.columns`. You can get
// `numeric_precision` and `numeric_scale` as well from there so you
// don't have to guess.
// Get oid of table, and approx number of pages for the relation.
let mut rows = self
.client
.query(
"
SELECT
pg_class.oid,
GREATEST(relpages, 1)
FROM pg_class INNER JOIN pg_namespace ON relnamespace = pg_namespace.oid
WHERE nspname=$1 AND relname=$2;
",
&[&schema, &name],
)
.await?;
// Should only return 0 or 1 row. If 0 rows, then table/schema doesn't
// exist.
let row = match rows.pop() {
Some(row) => row,
None => {
return Err(PostgresError::QueryError(format!(
"failed to find table: '{schema}.{name}'"
)))
}
};
let oid: u32 = row.try_get(0)?;
// TODO: Get approx pages to allow us to calculate number of pages to
// scan per thread once we do parallel scanning.
// let approx_pages: i64 = row.try_get(1)?;
// Get table schema.
let rows = self
.client
.query(
"
SELECT
attname,
pg_type.oid
FROM pg_attribute
INNER JOIN pg_type ON atttypid=pg_type.oid
WHERE attrelid=$1 AND attnum > 0
ORDER BY attnum;
",
&[&oid],
)
.await?;
let mut names: Vec<String> = Vec::with_capacity(rows.len());
let mut type_oids: Vec<u32> = Vec::with_capacity(rows.len());
for row in rows {
names.push(row.try_get(0)?);
type_oids.push(row.try_get(1)?);
}
let mut unknown_type_oids: Vec<u32> = Vec::new();
type_oids.iter().for_each(|oid| {
if PostgresType::from_oid(*oid).is_none() {
unknown_type_oids.push(*oid);
}
});
if !unknown_type_oids.is_empty() {
return Err(PostgresError::UnknownPostgresOids(unknown_type_oids));
}
//will Proceed here ONLY if types are known for all oids else returns error with unknown_type_oids
let pg_types = type_oids
.iter()
.map(|oid| PostgresType::from_oid(*oid))
.collect::<Option<Vec<_>>>()
.ok_or(PostgresError::UnknownPostgresOids(type_oids))?;
let arrow_schema = try_create_arrow_schema(names, &pg_types)?;
Ok((arrow_schema, pg_types))
}
}
#[async_trait]
impl VirtualLister for PostgresAccessState {
async fn list_schemas(&self) -> Result<Vec<String>, ExtensionError> {
use ExtensionError::ListingErrBoxed;
let rows = self
.client
.query("SELECT schema_name FROM information_schema.schemata", &[])
.await
.map_err(|e| ListingErrBoxed(Box::new(PostgresError::from(e))))?;
let mut schema_names: Vec<String> = Vec::with_capacity(rows.len());
for row in rows {
schema_names.push(
row.try_get(0)
.map_err(|e| ListingErrBoxed(Box::new(PostgresError::from(e))))?,
)
}
Ok(schema_names)
}
async fn list_tables(&self, schema: &str) -> Result<Vec<String>, ExtensionError> {
use ExtensionError::ListingErrBoxed;
let rows = self
.client
.query(
"
SELECT table_name
FROM information_schema.tables
WHERE
table_schema = $1
",
&[&schema],
)
.await
.map_err(|e| ListingErrBoxed(Box::new(PostgresError::from(e))))?;
let mut virtual_tables = Vec::with_capacity(rows.len());
for row in rows {
let table = row
.try_get(0)
.map_err(|e| ListingErrBoxed(Box::new(PostgresError::from(e))))?;
virtual_tables.push(table);
}
Ok(virtual_tables)
}
async fn list_columns(&self, schema: &str, table: &str) -> Result<Fields, ExtensionError> {
use ExtensionError::ListingErrBoxed;
let (schema, _) = self
.get_table_schema(schema, table)
.await
.map_err(|e| ListingErrBoxed(Box::new(e)))?;
Ok(schema.fields)
}
}
pub struct PostgresTableProviderConfig {
pub access: PostgresAccess,
pub schema: String,
pub table: String,
}
impl TryFrom<protogen::sqlexec::table_provider::PostgresTableProviderConfig>
for PostgresTableProviderConfig
{
type Error = ProtoConvError;
fn try_from(
value: protogen::sqlexec::table_provider::PostgresTableProviderConfig,
) -> std::result::Result<Self, Self::Error> {
Ok(Self {
access: value.access.required("postgres access")?,
schema: value.schema,
table: value.table,
})
}
}
impl From<PostgresTableProviderConfig>
for protogen::sqlexec::table_provider::PostgresTableProviderConfig
{
fn from(value: PostgresTableProviderConfig) -> Self {
Self {
access: Some(value.access.into()),
schema: value.schema,
table: value.table,
}
}
}
/// Table provider for a single postgres table.
pub struct PostgresTableProvider {
/// Schema name of table we're accessing.
schema: String,
/// Table we're accessing.
table: String,
state: Arc<PostgresAccessState>,
arrow_schema: ArrowSchemaRef,
pg_types: Arc<Vec<PostgresType>>,
}
impl PostgresTableProvider {
/// Try to create a new postgres table provider.
///
/// If postgres access state (client) isn't provided, a new one will be
/// created.
pub async fn try_new(conf: PostgresTableProviderConfig) -> Result<Self> {
let PostgresTableProviderConfig {
access,
schema,
table,
} = conf;
let state = Arc::new(access.connect().await?);
let (arrow_schema, pg_types) = state.get_table_schema(&schema, &table).await?;
Ok(PostgresTableProvider {
schema,
table,
state,
arrow_schema: Arc::new(arrow_schema),
pg_types: Arc::new(pg_types),
})
}
}
#[async_trait]
impl TableProvider for PostgresTableProvider {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> ArrowSchemaRef {
self.arrow_schema.clone()
}
fn table_type(&self) -> TableType {
TableType::Base
}
fn supports_filter_pushdown(
&self,
_filter: &Expr,
) -> DatafusionResult<TableProviderFilterPushDown> {
Ok(TableProviderFilterPushDown::Inexact)
}
async fn scan(
&self,
_ctx: &SessionState,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
) -> DatafusionResult<Arc<dyn ExecutionPlan>> {
// Project the schema.
let projected_schema = match projection {
Some(projection) => Arc::new(self.arrow_schema.project(projection)?),
None => self.arrow_schema.clone(),
};
// Project the postgres types so that it matches the ouput schema.
let projected_types = match projection {
Some(projection) => Arc::new(
projection
.iter()
.map(|i| self.pg_types[*i].clone())
.collect::<Vec<_>>(),
),
None => self.pg_types.clone(),
};
// Get the projected columns, joined by a ','. This will be put in the
// 'SELECT ...' portion of the query.
let projection_string = projected_schema
.fields
.iter()
.map(|f| f.name().clone())
.collect::<Vec<_>>()
.join(",");
let limit_string = match limit {
Some(limit) => format!("LIMIT {}", limit),
None => String::new(),
};
// Build WHERE clause if predicate pushdown enabled.
//
// TODO: This may produce an invalid clause. We'll likely only want to
// convert some predicates.
let predicate_string = {
exprs_to_predicate_string(filters)
.map_err(|e| DataFusionError::External(Box::new(e)))?
};
// Build copy query.
let query = format!(
"COPY (SELECT {} FROM {}.{} {} {} {}) TO STDOUT (FORMAT binary)",
projection_string, // SELECT <str>
self.schema, // FROM <schema>
self.table, // .<table>
// [WHERE]
if predicate_string.is_empty() {
""
} else {
"WHERE "
},
predicate_string.as_str(), // <where-predicate>
limit_string, // [LIMIT ..]
);
let exec = PostgresBinaryCopyExec::try_new(BinaryCopyConfig::State {
copy_query: query,
state: self.state.clone(),
pg_types: projected_types,
arrow_schema: projected_schema,
})
.await
.unwrap(); // Should never error.
Ok(Arc::new(exec))
}
async fn insert_into(
&self,
state: &SessionState,
input: Arc<dyn ExecutionPlan>,
_overwrite: bool,
) -> DatafusionResult<Arc<dyn ExecutionPlan>> {
let mut values = String::new();
let mut input = execute_stream(input, state.task_ctx())?;
while let Some(batch) = input.next().await {
let batch = batch?;
let mut row_sep = "";
for row_idx in 0..batch.num_rows() {
write!(&mut values, "{row_sep}(")?;
row_sep = ",";
let mut col_sep = "";
for col in batch.columns() {
write!(&mut values, "{col_sep}")?;
col_sep = ",";
let val = ScalarValue::try_from_array(col.as_ref(), row_idx)?;
util::encode_literal_to_text(util::Datasource::Postgres, &mut values, &val)
.map_err(|e| DataFusionError::External(Box::new(e)))?;
}
write!(&mut values, ")")?;
}
}
if values.is_empty() {
let batch = create_count_record_batch(0);
let schema = batch.schema();
return Ok(Arc::new(MemoryExec::try_new(&[vec![batch]], schema, None)?));
}
let query = format!(
"INSERT INTO {}.{} VALUES {}",
self.schema, self.table, values
);
debug!(%query, "inserting into postgres datasource");
let exec = PostgresQueryExec::new(query, self.state.clone());
Ok(Arc::new(exec))
}
}
#[derive(Debug, Clone)]
pub enum BinaryCopyConfig {
/// Serializable config.
AccessOnly {
access: Box<PostgresAccess>,
schema: String,
table: String,
copy_query: String,
},
/// Not serializable config.
State {
copy_query: String,
state: Arc<PostgresAccessState>,
pg_types: Arc<Vec<PostgresType>>,
arrow_schema: ArrowSchemaRef,
},
}
impl TryFrom<protogen::sqlexec::physical_plan::PostgresBinaryCopyConfig> for BinaryCopyConfig {
type Error = ProtoConvError;
fn try_from(
value: protogen::sqlexec::physical_plan::PostgresBinaryCopyConfig,
) -> std::result::Result<Self, Self::Error> {
Ok(Self::AccessOnly {
access: Box::new(value.access.required("postgres access")?),
schema: value.schema,
table: value.table,
copy_query: value.copy_query,
})
}
}
impl TryFrom<BinaryCopyConfig> for protogen::sqlexec::physical_plan::PostgresBinaryCopyConfig {
type Error = ProtoConvError;
fn try_from(value: BinaryCopyConfig) -> std::result::Result<Self, Self::Error> {
match value {
BinaryCopyConfig::State { .. } => Err(ProtoConvError::UnsupportedSerialization(
"cannot serialize a stateful binary copy config",
)),
BinaryCopyConfig::AccessOnly {
access,
schema,
table,
copy_query,
} => Ok(Self {
access: Some((*access).into()),
schema,
table,
copy_query,
}),
}
}
}
/// Copy data from the source Postgres table using the binary copy protocol.
pub struct PostgresBinaryCopyExec {
pg_types: Arc<Vec<PostgresType>>,
arrow_schema: ArrowSchemaRef,
opener: StreamOpener,
metrics: ExecutionPlanMetricsSet,
}
impl PostgresBinaryCopyExec {
/// Try to create a new binary copy exec using the provided config.
pub async fn try_new(conf: BinaryCopyConfig) -> Result<Self> {
match conf {
BinaryCopyConfig::AccessOnly {
access,
schema,
table,
copy_query,
} => {
let state = Arc::new(access.connect().await?);
let (arrow_schema, pg_types) = state.get_table_schema(&schema, &table).await?;
let opener = StreamOpener { copy_query, state };
Ok(PostgresBinaryCopyExec {
pg_types: Arc::new(pg_types),
arrow_schema: Arc::new(arrow_schema),
opener,
metrics: ExecutionPlanMetricsSet::new(),
})
}
BinaryCopyConfig::State {
copy_query,
state,
pg_types,
arrow_schema,
} => {
let opener = StreamOpener { copy_query, state };
Ok(PostgresBinaryCopyExec {
pg_types,
arrow_schema,
opener,
metrics: ExecutionPlanMetricsSet::new(),
})
}
}
}
}
impl ExecutionPlan for PostgresBinaryCopyExec {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> ArrowSchemaRef {
self.arrow_schema.clone()
}
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(1)
}
fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {
None
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
Vec::new()
}
fn with_new_children(
self: Arc<Self>,
_children: Vec<Arc<dyn ExecutionPlan>>,
) -> DatafusionResult<Arc<dyn ExecutionPlan>> {
Err(DataFusionError::Execution(
"cannot replace children for PostgresBinaryCopyExec".to_string(),
))
}
fn execute(
&self,
partition: usize,
_context: Arc<TaskContext>,
) -> DatafusionResult<SendableRecordBatchStream> {
let stream = ChunkStream {
state: StreamState::Idle,
types: self.pg_types.clone(),
opener: self.opener.clone(),
arrow_schema: self.arrow_schema.clone(),
};
Ok(Box::pin(DataSourceMetricsStreamAdapter::new(
stream,
partition,
&self.metrics,
)))
}
fn statistics(&self) -> Statistics {
Statistics::default()
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner())
}
}
impl DisplayAs for PostgresBinaryCopyExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PostgresBinaryCopyExec",)
}
}
impl fmt::Debug for PostgresBinaryCopyExec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PostgresBinaryCopyExec")
.field("pg_types", &self.pg_types)
.field("arrow_schema", &self.arrow_schema)
.finish()
}
}
/// Open a copy stream.
#[derive(Clone)]
struct StreamOpener {
/// Query used to initiate the binary copy.
copy_query: String,
state: Arc<PostgresAccessState>,
}
impl StreamOpener {
/// Build a future that returns the copy stream.
fn open(&self) -> BoxFuture<'static, Result<CopyOutStream, tokio_postgres::Error>> {
let query = self.copy_query.clone();
let accessor = self.state.clone();
Box::pin(async move { accessor.client.copy_out(&query).await })
}
}
/// Stream state.
///
/// Transitions:
/// Idle -> Open
/// Open -> Scan
/// Scan -> Done
///
/// 'Open' or 'Scan' may also transition to the 'Error' state. The stream is
/// complete once it has reached either 'Done' or 'Error'.
enum StreamState {
/// Initial state.
Idle,
/// Open the copy stream.
Open {
fut: BoxFuture<'static, Result<CopyOutStream, tokio_postgres::Error>>,
},
/// Binary copy scan ongoing.
Scan {
stream: BoxStream<'static, Vec<Result<BinaryCopyOutRow, tokio_postgres::Error>>>,
},
/// Scan finished.
Done,
/// Scan encountered an error.
Error,
}
struct ChunkStream {
/// The currently state of the stream.
state: StreamState,
/// Postgres types we're scanning from the binary copy stream.
types: Arc<Vec<PostgresType>>,
/// Opens the copy stream.
opener: StreamOpener,
/// Schema of the resulting record batch.
arrow_schema: ArrowSchemaRef,
}
impl Stream for ChunkStream {
type Item = DatafusionResult<RecordBatch>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match &mut self.state {
StreamState::Idle => {
let fut = self.opener.open();
self.state = StreamState::Open { fut };
}
StreamState::Open { fut } => match ready!(fut.poll_unpin(cx)) {
Ok(stream) => {
// Get the binary stream from postgres.
let stream = BinaryCopyOutStream::new(stream, &self.types);
// Chunk the rows. We'll be returning a single record
// batch per chunk.
let chunked = stream.chunks(1000); // TODO: Make configurable.
self.state = StreamState::Scan {
stream: chunked.boxed(),
};
}
Err(e) => {
self.state = StreamState::Error;
return Poll::Ready(Some(Err(DataFusionError::External(Box::new(e)))));
}
},
StreamState::Scan { stream } => match ready!(stream.poll_next_unpin(cx)) {
Some(rows) => {
match binary_rows_to_record_batch(rows, self.arrow_schema.clone()) {
Ok(batch) => {
return Poll::Ready(Some(Ok(batch)));
}
Err(e) => {
self.state = StreamState::Error;
return Poll::Ready(Some(Err(DataFusionError::External(
Box::new(e),
))));
}
}
}
None => {
self.state = StreamState::Done;
}
},
StreamState::Done | StreamState::Error => return Poll::Ready(None),
}
}
}
}
impl RecordBatchStream for ChunkStream {
fn schema(&self) -> ArrowSchemaRef {
self.arrow_schema.clone()
}
}
/// Str is a wrapper to represent multiple datatypes as arrow
/// `DataType::Utf8`, i.e., a string.
struct Str<'a>(Cow<'a, str>);
impl<'a> Borrow<str> for Str<'a> {