-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathduckdb.rs
More file actions
1120 lines (943 loc) · 38.3 KB
/
duckdb.rs
File metadata and controls
1120 lines (943 loc) · 38.3 KB
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
use crate::duckdb::write_settings::DuckDBWriteSettings;
use crate::sql::sql_provider_datafusion;
use crate::util::supported_functions::FunctionSupport;
use crate::util::{
self,
column_reference::{self, ColumnReference},
constraints,
indexes::IndexType,
on_conflict::{self, OnConflict},
};
use crate::{
sql::db_connection_pool::{
self,
dbconnection::{
duckdbconn::{
flatten_table_function_name, is_table_function, DuckDBParameter, DuckDbConnection,
},
get_schema, DbConnection,
},
duckdbpool::{DuckDbConnectionPool, DuckDbConnectionPoolBuilder},
DbConnectionPool, DbInstanceKey, Mode,
},
UnsupportedTypeAction,
};
use arrow::datatypes::SchemaRef;
use async_trait::async_trait;
use datafusion::sql::unparser::dialect::{Dialect, DuckDBDialect};
use datafusion::{
catalog::{Session, TableProviderFactory},
common::Constraints,
datasource::TableProvider,
error::{DataFusionError, Result as DataFusionResult},
logical_expr::CreateExternalTable,
sql::TableReference,
};
use duckdb::{AccessMode, DuckdbConnectionManager};
use itertools::Itertools;
use snafu::prelude::*;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
use write::DuckDBTableWriterBuilder;
pub use self::settings::{
DuckDBSetting, DuckDBSettingScope, DuckDBSettingsRegistry, MemoryLimitSetting,
PreserveInsertionOrderSetting, TempDirectorySetting,
};
use self::sql_table::DuckDBTable;
#[cfg(feature = "duckdb-federation")]
mod federation;
mod creator;
mod settings;
pub mod sql_table;
pub mod write;
pub mod write_settings;
pub use creator::{RelationName, TableDefinition, TableManager, ViewCreator};
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("DbConnectionError: {source}"))]
DbConnectionError {
source: db_connection_pool::dbconnection::GenericError,
},
#[snafu(display("DbConnectionPoolError: {source}"))]
DbConnectionPoolError { source: db_connection_pool::Error },
#[snafu(display("DuckDBDataFusionError: {source}"))]
DuckDBDataFusion {
source: sql_provider_datafusion::Error,
},
#[snafu(display("Unable to downcast DbConnection to DuckDbConnection"))]
UnableToDowncastDbConnection {},
#[snafu(display("Unable to drop duckdb table: {source}"))]
UnableToDropDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to create duckdb table: {source}"))]
UnableToCreateDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to create index on duckdb table: {source}"))]
UnableToCreateIndexOnDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to retrieve existing primary keys from DuckDB table: {source}"))]
UnableToGetPrimaryKeysOnDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to drop index on duckdb table: {source}"))]
UnableToDropIndexOnDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to rename duckdb table: {source}"))]
UnableToRenameDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to insert into duckdb table: {source}"))]
UnableToInsertToDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to get appender to duckdb table: {source}"))]
UnableToGetAppenderToDuckDBTable { source: duckdb::Error },
#[snafu(display("Unable to delete data from the duckdb table: {source}"))]
UnableToDeleteDuckdbData { source: duckdb::Error },
#[snafu(display("Unable to query data from the duckdb table: {source}"))]
UnableToQueryData { source: duckdb::Error },
#[snafu(display("Unable to commit transaction: {source}"))]
UnableToCommitTransaction { source: duckdb::Error },
#[snafu(display("Unable to begin duckdb transaction: {source}"))]
UnableToBeginTransaction { source: duckdb::Error },
#[snafu(display("Unable to rollback transaction: {source}"))]
UnableToRollbackTransaction { source: duckdb::Error },
#[snafu(display("Unable to delete all data from the DuckDB table: {source}"))]
UnableToDeleteAllTableData { source: duckdb::Error },
#[snafu(display("Unable to insert data into the DuckDB table: {source}"))]
UnableToInsertIntoTableAsync { source: duckdb::Error },
#[snafu(display("The table '{table_name}' doesn't exist in the DuckDB server"))]
TableDoesntExist { table_name: String },
#[snafu(display("Constraint Violation: {source}"))]
ConstraintViolation { source: constraints::Error },
#[snafu(display("Error parsing column reference: {source}"))]
UnableToParseColumnReference { source: column_reference::Error },
#[snafu(display("Error parsing on_conflict: {source}"))]
UnableToParseOnConflict { source: on_conflict::Error },
#[snafu(display(
"Failed to create '{table_name}': creating a table with a schema is not supported"
))]
TableWithSchemaCreationNotSupported { table_name: String },
#[snafu(display("Failed to parse memory_limit value '{value}': {source}\nProvide a valid value, e.g. '2GB', '512MiB' (expected: KB, MB, GB, TB for 1000^i units or KiB, MiB, GiB, TiB for 1024^i units)"))]
UnableToParseMemoryLimit {
value: String,
source: byte_unit::ParseError,
},
#[snafu(display("Unable to add primary key to table: {source}"))]
UnableToAddPrimaryKey { source: duckdb::Error },
#[snafu(display("Failed to get system time since epoch: {source}"))]
UnableToGetSystemTime { source: std::time::SystemTimeError },
#[snafu(display("Failed to parse the system time: {source}"))]
UnableToParseSystemTime { source: std::num::ParseIntError },
#[snafu(display("Failed to parse 'connection_pool_size' value '{value}': {source}. Provide a valid positive integer value, e.g. '10', '20' and try again."))]
UnableToParseConnectionPoolSize {
value: String,
source: std::num::ParseIntError,
},
#[snafu(display("A read provider is required to create a DuckDBTableWriter"))]
MissingReadProvider,
#[snafu(display("A pool is required to create a DuckDBTableWriter"))]
MissingPool,
#[snafu(display("A table definition is required to create a DuckDBTableWriter"))]
MissingTableDefinition,
#[snafu(display("Failed to register Arrow scan view for DuckDB ingestion: {source}"))]
UnableToRegisterArrowScanView { source: duckdb::Error },
#[snafu(display(
"Failed to register Arrow scan view to build table creation statement: {source}"
))]
UnableToRegisterArrowScanViewForTableCreation { source: duckdb::Error },
#[snafu(display("Failed to drop Arrow scan view for DuckDB ingestion: {source}"))]
UnableToDropArrowScanView { source: duckdb::Error },
}
type Result<T, E = Error> = std::result::Result<T, E>;
const DUCKDB_DB_PATH_PARAM: &str = "open";
const DUCKDB_DB_BASE_FOLDER_PARAM: &str = "data_directory";
const DUCKDB_ATTACH_DATABASES_PARAM: &str = "attach_databases";
pub struct DuckDBTableProviderFactory {
access_mode: AccessMode,
instances: Arc<Mutex<HashMap<DbInstanceKey, DuckDbConnectionPool>>>,
unsupported_type_action: UnsupportedTypeAction,
dialect: Arc<dyn Dialect>,
settings_registry: DuckDBSettingsRegistry,
function_support: Option<FunctionSupport>,
}
// Dialect trait does not implement Debug so we implement Debug manually
impl std::fmt::Debug for DuckDBTableProviderFactory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DuckDBTableProviderFactory")
.field("access_mode", &self.access_mode)
.field("instances", &self.instances)
.field("unsupported_type_action", &self.unsupported_type_action)
.field("settings_registry", &self.settings_registry)
.finish()
}
}
impl DuckDBTableProviderFactory {
#[must_use]
pub fn new(access_mode: AccessMode) -> Self {
Self {
access_mode,
instances: Arc::new(Mutex::new(HashMap::new())),
unsupported_type_action: UnsupportedTypeAction::Error,
dialect: Arc::new(DuckDBDialect::new()),
settings_registry: DuckDBSettingsRegistry::new(),
function_support: None,
}
}
#[must_use]
pub fn with_function_support(mut self, function_support: FunctionSupport) -> Self {
self.function_support = Some(function_support);
self
}
#[must_use]
pub fn with_unsupported_type_action(
mut self,
unsupported_type_action: UnsupportedTypeAction,
) -> Self {
self.unsupported_type_action = unsupported_type_action;
self
}
#[must_use]
pub fn with_dialect(mut self, dialect: Arc<dyn Dialect + Send + Sync>) -> Self {
self.dialect = dialect;
self
}
#[must_use]
pub fn with_settings_registry(mut self, settings_registry: DuckDBSettingsRegistry) -> Self {
self.settings_registry = settings_registry;
self
}
#[must_use]
pub fn settings_registry(&self) -> &DuckDBSettingsRegistry {
&self.settings_registry
}
#[must_use]
pub fn settings_registry_mut(&mut self) -> &mut DuckDBSettingsRegistry {
&mut self.settings_registry
}
#[must_use]
pub fn attach_databases(&self, options: &HashMap<String, String>) -> Vec<Arc<str>> {
options
.get(DUCKDB_ATTACH_DATABASES_PARAM)
.map(|attach_databases| {
attach_databases
.split(';')
.map(Arc::from)
.collect::<Vec<Arc<str>>>()
})
.unwrap_or_default()
}
/// Get the path to the DuckDB file database.
///
/// ## Errors
///
/// - If the path includes absolute sequences to escape the current directory, like `./`, `../`, or `/`.
pub fn duckdb_file_path(
&self,
name: &str,
options: &mut HashMap<String, String>,
) -> Result<String, Error> {
let options = util::remove_prefix_from_hashmap_keys(options.clone(), "duckdb_");
let db_base_folder = options
.get(DUCKDB_DB_BASE_FOLDER_PARAM)
.cloned()
.unwrap_or(".".to_string()); // default to the current directory
let default_filepath = &format!("{db_base_folder}/{name}.db");
let filepath = options
.get(DUCKDB_DB_PATH_PARAM)
.unwrap_or(default_filepath);
Ok(filepath.to_string())
}
pub async fn get_or_init_memory_instance(
&self,
options: &HashMap<String, String>,
) -> Result<DuckDbConnectionPool> {
let mut pool_builder = DuckDbConnectionPoolBuilder::memory();
if let Some(max_size) = extract_connection_pool_size(options)? {
pool_builder = pool_builder.with_max_size(Some(max_size));
}
self.get_or_init_instance_with_builder(pool_builder).await
}
pub async fn get_or_init_file_instance(
&self,
db_path: impl Into<Arc<str>>,
options: &HashMap<String, String>,
) -> Result<DuckDbConnectionPool> {
let db_path: Arc<str> = db_path.into();
let mut pool_builder = DuckDbConnectionPoolBuilder::file(&db_path);
if let Some(max_size) = extract_connection_pool_size(options)? {
pool_builder = pool_builder.with_max_size(Some(max_size));
}
self.get_or_init_instance_with_builder(pool_builder).await
}
pub async fn get_or_init_instance_with_builder(
&self,
pool_builder: DuckDbConnectionPoolBuilder,
) -> Result<DuckDbConnectionPool> {
let mode = pool_builder.get_mode();
let key = match mode {
Mode::File => {
let path = pool_builder.get_path();
DbInstanceKey::file(path.into())
}
Mode::Memory => DbInstanceKey::memory(),
};
let access_mode = match &self.access_mode {
AccessMode::ReadOnly => AccessMode::ReadOnly,
AccessMode::ReadWrite => AccessMode::ReadWrite,
AccessMode::Automatic => AccessMode::Automatic,
};
let pool_builder = pool_builder.with_access_mode(access_mode);
let mut instances = self.instances.lock().await;
if let Some(instance) = instances.get(&key) {
return Ok(instance.clone());
}
let pool = pool_builder
.build()
.context(DbConnectionPoolSnafu)?
.with_unsupported_type_action(self.unsupported_type_action);
instances.insert(key, pool.clone());
Ok(pool)
}
/// Drop the cached pool entry for `key` if any, returning the previously
/// cached pool. Subsequent calls to `get_or_init_*` for the same key will
/// build a fresh pool.
///
/// This is intended for callers that replace the underlying database file
/// out-of-band (for example, after restoring it from a snapshot in object
/// storage). Existing connections held by other clones of the previously
/// returned pool keep operating against the file descriptor they opened;
/// once they are dropped the OS releases the prior inode. New providers
/// built after invalidation will open the file fresh and observe the
/// replacement contents.
pub async fn invalidate_instance(&self, key: &DbInstanceKey) -> Option<DuckDbConnectionPool> {
self.instances.lock().await.remove(key)
}
/// Drop the cached pool entry for the file at `path` if any.
///
/// Convenience wrapper over [`Self::invalidate_instance`] for the common
/// file-mode case.
pub async fn invalidate_file_instance(
&self,
path: impl Into<Arc<str>>,
) -> Option<DuckDbConnectionPool> {
self.invalidate_instance(&DbInstanceKey::file(path.into()))
.await
}
}
type DynDuckDbConnectionPool = dyn DbConnectionPool<r2d2::PooledConnection<DuckdbConnectionManager>, DuckDBParameter>
+ Send
+ Sync;
#[async_trait]
impl TableProviderFactory for DuckDBTableProviderFactory {
#[allow(clippy::too_many_lines)]
async fn create(
&self,
_state: &dyn Session,
cmd: &CreateExternalTable,
) -> DataFusionResult<Arc<dyn TableProvider>> {
if cmd.name.schema().is_some() {
TableWithSchemaCreationNotSupportedSnafu {
table_name: cmd.name.to_string(),
}
.fail()
.map_err(to_datafusion_error)?;
}
let name = cmd.name.to_string();
let mut options = cmd.options.clone();
let mode = remove_option(&mut options, "mode").unwrap_or_default();
let mode: Mode = mode.as_str().into();
let indexes_option_str = remove_option(&mut options, "indexes");
let unparsed_indexes: HashMap<String, IndexType> = match indexes_option_str {
Some(indexes_str) => util::hashmap_from_option_string(&indexes_str),
None => HashMap::new(),
};
let unparsed_indexes = unparsed_indexes
.into_iter()
.map(|(key, value)| {
let columns = ColumnReference::try_from(key.as_str())
.context(UnableToParseColumnReferenceSnafu)
.map_err(to_datafusion_error);
(columns, value)
})
.collect::<Vec<(Result<ColumnReference, DataFusionError>, IndexType)>>();
let mut indexes: Vec<(ColumnReference, IndexType)> = Vec::new();
for (columns, index_type) in unparsed_indexes {
let columns = columns?;
indexes.push((columns, index_type));
}
let mut on_conflict: Option<OnConflict> = None;
if let Some(on_conflict_str) = remove_option(&mut options, "on_conflict") {
on_conflict = Some(
OnConflict::try_from(on_conflict_str.as_str())
.context(UnableToParseOnConflictSnafu)
.map_err(to_datafusion_error)?,
);
}
let pool: DuckDbConnectionPool = match &mode {
Mode::File => {
// open duckdb at given path or create a new one
let db_path = self
.duckdb_file_path(&name, &mut options)
.map_err(to_datafusion_error)?;
self.get_or_init_file_instance(db_path, &options)
.await
.map_err(to_datafusion_error)?
}
Mode::Memory => self
.get_or_init_memory_instance(&options)
.await
.map_err(to_datafusion_error)?,
};
let read_pool = match &mode {
Mode::File => {
let read_pool = pool.clone();
read_pool
.set_attached_databases(&self.attach_databases(&options))
.context(DbConnectionPoolSnafu)
.map_err(to_datafusion_error)?
}
Mode::Memory => pool.clone(),
};
// Get local DuckDB SET statements to use as setup queries on the pool
let local_settings = self
.settings_registry
.get_setting_statements(&options, DuckDBSettingScope::Local);
let read_pool = read_pool.with_connection_setup_queries(local_settings);
let schema: SchemaRef = Arc::new(cmd.schema.as_ref().as_arrow().clone());
let table_definition =
TableDefinition::new(RelationName::new(name.clone()), Arc::clone(&schema))
.with_constraints(cmd.constraints.clone())
.with_indexes(indexes.clone());
let pool = Arc::new(pool);
make_initial_table(Arc::new(table_definition.clone()), &pool)?;
let write_settings = DuckDBWriteSettings::from_params(&options);
let table_writer_builder = DuckDBTableWriterBuilder::new()
.with_table_definition(table_definition)
.with_pool(pool)
.set_on_conflict(on_conflict)
.with_write_settings(write_settings);
let dyn_pool: Arc<DynDuckDbConnectionPool> = Arc::new(read_pool);
let db_conn = dyn_pool.connect().await?;
let Some(conn) = db_conn.as_sync() else {
return Err(DataFusionError::External(Box::new(
Error::DbConnectionError {
source: "Failed to get sync DuckDbConnection using DbConnection".into(),
},
)));
};
// Apply DuckDB global settings
self.settings_registry
.apply_settings(conn, &options, DuckDBSettingScope::Global)?;
let read_provider = Arc::new(DuckDBTable::new_with_schema(
&dyn_pool,
Arc::clone(&schema),
TableReference::bare(name.clone()),
None,
Some(self.dialect.clone()),
Some(cmd.constraints.clone()),
self.function_support.clone(),
indexes,
));
#[cfg(feature = "duckdb-federation")]
let read_provider: Arc<dyn TableProvider> =
Arc::new(read_provider.create_federated_table_provider()?);
Ok(Arc::new(
table_writer_builder
.with_read_provider(read_provider)
.build()
.map_err(to_datafusion_error)?,
))
}
}
fn to_datafusion_error(error: Error) -> DataFusionError {
DataFusionError::External(Box::new(error))
}
pub struct DuckDB {
table_name: String,
pool: Arc<DuckDbConnectionPool>,
schema: SchemaRef,
constraints: Constraints,
}
impl std::fmt::Debug for DuckDB {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DuckDB")
.field("table_name", &self.table_name)
.field("schema", &self.schema)
.field("constraints", &self.constraints)
.finish()
}
}
impl DuckDB {
#[must_use]
pub fn existing_table(
table_name: String,
pool: Arc<DuckDbConnectionPool>,
schema: SchemaRef,
constraints: Constraints,
) -> Self {
Self {
table_name,
pool,
schema,
constraints,
}
}
#[must_use]
pub fn table_name(&self) -> &str {
&self.table_name
}
#[must_use]
pub fn constraints(&self) -> &Constraints {
&self.constraints
}
pub fn connect_sync(
&self,
) -> Result<
Box<dyn DbConnection<r2d2::PooledConnection<DuckdbConnectionManager>, DuckDBParameter>>,
> {
Arc::clone(&self.pool)
.connect_sync()
.context(DbConnectionSnafu)
}
pub fn duckdb_conn(
db_connection: &mut Box<
dyn DbConnection<r2d2::PooledConnection<DuckdbConnectionManager>, DuckDBParameter>,
>,
) -> Result<&mut DuckDbConnection> {
db_connection
.as_any_mut()
.downcast_mut::<DuckDbConnection>()
.context(UnableToDowncastDbConnectionSnafu)
}
}
fn remove_option(options: &mut HashMap<String, String>, key: &str) -> Option<String> {
options
.remove(key)
.or_else(|| options.remove(&format!("duckdb.{key}")))
}
fn extract_connection_pool_size(options: &HashMap<String, String>) -> Result<Option<u32>> {
if let Some(pool_size_str) = options.get("connection_pool_size") {
pool_size_str
.parse()
.context(UnableToParseConnectionPoolSizeSnafu {
value: pool_size_str.clone(),
})
.map(Some)
} else {
Ok(None)
}
}
pub struct DuckDBTableFactory {
pool: Arc<DuckDbConnectionPool>,
dialect: Arc<dyn Dialect>,
schema: Option<SchemaRef>,
function_support: Option<FunctionSupport>,
indexes: Vec<(ColumnReference, IndexType)>,
}
impl DuckDBTableFactory {
#[must_use]
pub fn new(pool: Arc<DuckDbConnectionPool>) -> Self {
Self {
pool,
dialect: Arc::new(DuckDBDialect::new()),
schema: None,
function_support: None,
indexes: vec![],
}
}
#[must_use]
pub fn with_function_support(mut self, function_support: FunctionSupport) -> Self {
self.function_support = Some(function_support);
self
}
#[must_use]
pub fn with_dialect(mut self, dialect: Arc<dyn Dialect + Send + Sync>) -> Self {
self.dialect = dialect;
self
}
#[must_use]
pub fn with_schema(mut self, schema: SchemaRef) -> Self {
self.schema = Some(schema);
self
}
#[must_use]
pub fn with_indexes(mut self, indexes: Vec<(ColumnReference, IndexType)>) -> Self {
self.indexes = indexes;
self
}
pub async fn table_provider(
&self,
table_reference: TableReference,
) -> Result<Arc<dyn TableProvider + 'static>, Box<dyn std::error::Error + Send + Sync>> {
let pool = Arc::clone(&self.pool);
let conn = Arc::clone(&pool).connect().await?;
let dyn_pool: Arc<DynDuckDbConnectionPool> = pool;
let schema = match self.schema.as_ref() {
Some(schema) => Arc::clone(schema),
None => get_schema(conn, &table_reference).await?,
};
let (tbl_ref, cte) = if is_table_function(&table_reference) {
let tbl_ref_view = create_table_function_view_name(&table_reference);
(
tbl_ref_view.clone(),
Some(HashMap::from_iter(vec![(
tbl_ref_view.to_string(),
table_reference.table().to_string(),
)])),
)
} else {
(table_reference.clone(), None)
};
let table_provider = Arc::new(DuckDBTable::new_with_schema(
&dyn_pool,
schema,
tbl_ref,
cte,
Some(self.dialect.clone()),
None,
self.function_support.clone(),
self.indexes.clone(),
));
#[cfg(feature = "duckdb-federation")]
let table_provider: Arc<dyn TableProvider> =
Arc::new(table_provider.create_federated_table_provider()?);
Ok(table_provider)
}
pub async fn read_write_table_provider(
&self,
table_reference: TableReference,
) -> Result<Arc<dyn TableProvider + 'static>, Box<dyn std::error::Error + Send + Sync>> {
let read_provider = Self::table_provider(self, table_reference.clone()).await?;
let schema = read_provider.schema();
let table_name = RelationName::from(table_reference);
let table_definition = TableDefinition::new(table_name, Arc::clone(&schema));
let table_writer_builder = DuckDBTableWriterBuilder::new()
.with_read_provider(read_provider)
.with_pool(Arc::clone(&self.pool))
.with_table_definition(table_definition);
Ok(Arc::new(table_writer_builder.build()?))
}
}
/// For a [`TableReference`] that is a table function, create a name for a view on the original [`TableReference`]
///
/// ### Example
///
/// ```rust,ignore
/// use datafusion_table_providers::duckdb::create_table_function_view_name;
/// use datafusion::common::TableReference;
///
/// let table_reference = TableReference::from("catalog.schema.read_parquet('cleaned_sales_data.parquet')");
/// let view_name = create_table_function_view_name(&table_reference);
/// assert_eq!(view_name.to_string(), "catalog.schema.read_parquet_cleaned_sales_dataparquet__view");
/// ```
fn create_table_function_view_name(table_reference: &TableReference) -> TableReference {
let tbl_ref_view = [
table_reference.catalog(),
table_reference.schema(),
Some(&flatten_table_function_name(table_reference)),
]
.iter()
.flatten()
.join(".");
TableReference::from(&tbl_ref_view)
}
pub(crate) fn make_initial_table(
table_definition: Arc<TableDefinition>,
pool: &Arc<DuckDbConnectionPool>,
) -> DataFusionResult<()> {
let cloned_pool = Arc::clone(pool);
let mut db_conn = Arc::clone(&cloned_pool)
.connect_sync()
.context(DbConnectionPoolSnafu)
.map_err(to_datafusion_error)?;
let duckdb_conn = DuckDB::duckdb_conn(&mut db_conn).map_err(to_datafusion_error)?;
let tx = duckdb_conn
.conn
.transaction()
.context(UnableToBeginTransactionSnafu)
.map_err(to_datafusion_error)?;
let has_table = table_definition
.has_table(&tx)
.map_err(to_datafusion_error)?;
let internal_tables = table_definition
.list_internal_tables(&tx)
.map_err(to_datafusion_error)?;
if has_table || !internal_tables.is_empty() {
return Ok(());
}
let table_manager = TableManager::new(table_definition);
table_manager
.create_table(cloned_pool, &tx)
.map_err(to_datafusion_error)?;
tx.commit()
.context(UnableToCommitTransactionSnafu)
.map_err(to_datafusion_error)?;
Ok(())
}
#[cfg(test)]
pub(crate) mod tests {
use crate::duckdb::write::DuckDBTableWriter;
use super::*;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::{Constraints, ToDFSchema};
use datafusion::logical_expr::CreateExternalTable;
use datafusion::prelude::SessionContext;
use datafusion::sql::TableReference;
use std::collections::HashMap;
use std::sync::Arc;
#[tokio::test]
async fn invalidate_instance_drops_cached_pool() {
let factory = DuckDBTableProviderFactory::new(duckdb::AccessMode::ReadWrite);
let options = HashMap::new();
// First call populates the cache.
let _pool1 = factory
.get_or_init_memory_instance(&options)
.await
.expect("first init");
assert_eq!(factory.instances.lock().await.len(), 1);
// Second call (without invalidation) returns the cached pool clone
// without growing the registry.
let _pool2 = factory
.get_or_init_memory_instance(&options)
.await
.expect("cached init");
assert_eq!(factory.instances.lock().await.len(), 1);
// Invalidate; entry is evicted and returned.
let evicted = factory.invalidate_instance(&DbInstanceKey::memory()).await;
assert!(evicted.is_some(), "invalidate returns evicted pool");
assert_eq!(factory.instances.lock().await.len(), 0);
// Re-invalidating a missing key is a no-op.
assert!(factory
.invalidate_instance(&DbInstanceKey::file("never-cached".into()))
.await
.is_none());
// Next get_or_init repopulates the cache.
let _pool3 = factory
.get_or_init_memory_instance(&options)
.await
.expect("reinit after invalidate");
assert_eq!(factory.instances.lock().await.len(), 1);
}
#[tokio::test]
async fn test_create_with_memory_limit() {
let table_name = TableReference::bare("test_table");
let schema = Schema::new(vec![Field::new("dummy", DataType::Int32, false)]);
let mut options = HashMap::new();
options.insert("mode".to_string(), "memory".to_string());
options.insert("memory_limit".to_string(), "123MiB".to_string());
let factory = DuckDBTableProviderFactory::new(duckdb::AccessMode::ReadWrite);
let ctx = SessionContext::new();
let cmd = CreateExternalTable {
schema: Arc::new(schema.to_dfschema().expect("to df schema")),
name: table_name,
location: "".to_string(),
file_type: "".to_string(),
table_partition_cols: vec![],
if_not_exists: false,
definition: None,
order_exprs: vec![],
unbounded: false,
options,
constraints: Constraints::default(),
column_defaults: HashMap::new(),
temporary: false,
or_replace: false,
};
let table_provider = factory
.create(&ctx.state(), &cmd)
.await
.expect("table provider created");
let writer = table_provider
.as_any()
.downcast_ref::<DuckDBTableWriter>()
.expect("cast to DuckDBTableWriter");
let mut conn_box = writer.pool().connect_sync().expect("to get connection");
let conn = DuckDB::duckdb_conn(&mut conn_box).expect("to get DuckDB connection");
let mut stmt = conn
.conn
.prepare("SELECT value FROM duckdb_settings() WHERE name = 'memory_limit'")
.expect("to prepare statement");
let memory_limit = stmt
.query_row([], |row| row.get::<usize, String>(0))
.expect("to query memory limit");
println!("Memory limit: {memory_limit}");
assert_eq!(
memory_limit, "123.0 MiB",
"Memory limit must be set to 123.0 MiB"
);
}
#[tokio::test]
async fn test_create_with_temp_directory() {
let table_name = TableReference::bare("test_table_temp_dir");
let schema = Schema::new(vec![Field::new("dummy", DataType::Int32, false)]);
let test_temp_directory = "/tmp/duckdb_test_temp";
let mut options = HashMap::new();
options.insert("mode".to_string(), "memory".to_string());
options.insert(
"temp_directory".to_string(),
test_temp_directory.to_string(),
);
let factory = DuckDBTableProviderFactory::new(duckdb::AccessMode::ReadWrite);
let ctx = SessionContext::new();
let cmd = CreateExternalTable {
schema: Arc::new(schema.to_dfschema().expect("to df schema")),
name: table_name,
location: "".to_string(),
file_type: "".to_string(),
table_partition_cols: vec![],
if_not_exists: false,
definition: None,
order_exprs: vec![],
unbounded: false,
options,
constraints: Constraints::default(),
column_defaults: HashMap::new(),
temporary: false,
or_replace: false,
};
let table_provider = factory
.create(&ctx.state(), &cmd)
.await
.expect("table provider created");
let writer = table_provider
.as_any()
.downcast_ref::<DuckDBTableWriter>()
.expect("cast to DuckDBTableWriter");
let mut conn_box = writer.pool().connect_sync().expect("to get connection");
let conn = DuckDB::duckdb_conn(&mut conn_box).expect("to get DuckDB connection");
let mut stmt = conn
.conn
.prepare("SELECT value FROM duckdb_settings() WHERE name = 'temp_directory'")
.expect("to prepare statement");
let temp_directory = stmt
.query_row([], |row| row.get::<usize, String>(0))
.expect("to query temp directory");
println!("Temp directory: {temp_directory}");
assert_eq!(
temp_directory, test_temp_directory,
"Temp directory must be set to {test_temp_directory}"
);
}
#[tokio::test]
async fn test_create_with_preserve_insertion_order_true() {
let table_name = TableReference::bare("test_table_preserve_order_true");
let schema = Schema::new(vec![Field::new("dummy", DataType::Int32, false)]);
let mut options = HashMap::new();
options.insert("mode".to_string(), "memory".to_string());
options.insert("preserve_insertion_order".to_string(), "true".to_string());
let factory = DuckDBTableProviderFactory::new(duckdb::AccessMode::ReadWrite);
let ctx = SessionContext::new();
let cmd = CreateExternalTable {
schema: Arc::new(schema.to_dfschema().expect("to df schema")),
name: table_name,
location: "".to_string(),
file_type: "".to_string(),
table_partition_cols: vec![],
if_not_exists: false,
definition: None,
order_exprs: vec![],
unbounded: false,
options,
constraints: Constraints::default(),
column_defaults: HashMap::new(),
temporary: false,
or_replace: false,
};
let table_provider = factory
.create(&ctx.state(), &cmd)
.await
.expect("table provider created");