-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathduckdb.rs
More file actions
2209 lines (1940 loc) · 80.1 KB
/
duckdb.rs
File metadata and controls
2209 lines (1940 loc) · 80.1 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
/*
Copyright 2024-2025 The Spice.ai OSS Authors
Licensed 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
https://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 super::{AccelerationSource, BootstrapStatus, DataAccelerator};
use crate::{
App, Runtime,
component::{
dataset::{
Dataset,
acceleration::{Acceleration, Engine, Mode, RefreshMode},
},
view::View,
},
dataaccelerator::{
FilePathError,
snapshots::{download_snapshot_if_needed, snapshot_before_recreate},
storage::{ResolvedAccelerationStorage, resolve_acceleration_storage_async},
},
datafusion::{
dialect::new_duckdb_dialect,
sort_columns::{SortColumn, parse_sort_columns},
udf::deny_spice_functions_for_duckdb,
},
make_spice_data_directory,
parameters::ParameterSpec,
register_data_accelerator, spice_data_base_path,
};
use async_trait::async_trait;
use data_components::poly::PolyTableProvider;
use datafusion::error::DataFusionError;
use datafusion::execution::runtime_env::RuntimeEnv;
use datafusion::{
catalog::TableProviderFactory,
datasource::TableProvider,
execution::context::SessionContext,
logical_expr::CreateExternalTable,
sql::sqlparser::ast::{
Delete, FromTable, Ident, ObjectName, ObjectNamePart, Statement as SQLStatement,
TableFactor,
},
};
use datafusion_table_providers::{
duckdb::{
DuckDB, DuckDBSettingsRegistry, DuckDBTableProviderFactory,
write::{DuckDBTableWriter, WriteCompletionHandler},
},
sql::db_connection_pool::{
self as db_connection_pool,
duckdbpool::{DuckDbConnectionPool, DuckDbConnectionPoolBuilder},
},
};
use duckdb::AccessMode;
use itertools::Itertools;
use runtime_acceleration::snapshot::AccelerationEngine;
use runtime_table_partition::expression::PartitionedBy;
use settings::OrderByNonIntegerLiteral;
use snafu::prelude::*;
use std::collections::HashMap;
use std::{
any::Any,
cmp::max,
collections::HashSet,
ffi::OsStr,
path::PathBuf,
sync::{Arc, Once},
};
pub(crate) mod settings;
/// Creates a [`DuckDBTableProviderFactory`] with standard Spice settings (dialect, timezone,
/// index scan tuning, function deny-list). All `DuckDB` accelerator consumers should use this
/// to avoid divergent configurations.
pub(crate) fn create_factory() -> DuckDBTableProviderFactory {
DuckDBTableProviderFactory::new(AccessMode::ReadWrite)
.with_dialect(new_duckdb_dialect())
.with_settings_registry(
DuckDBSettingsRegistry::new()
.with_setting(Box::new(OrderByNonIntegerLiteral))
.with_setting(Box::new(settings::IndexScanPercentage))
.with_setting(Box::new(settings::IndexScanMaxCount))
.with_setting(Box::new(settings::TimeZone)),
)
.with_function_support(deny_spice_functions_for_duckdb().as_ref().clone())
}
pub(crate) const DEFAULT_CONNECTION_POOL_SIZE: u32 = 10;
pub(crate) const DEFAULT_EBS_CONNECTION_POOL_SIZE: u32 = 4;
pub(crate) const SPICE_ACCELERATOR_METADATA_KEY: &str = "spice.accelerator";
pub(crate) const SPICE_OPT_DUCKDB_AGG_PUSHDOWN_KEY: &str =
"spice.optimizer.duckdb_aggregate_pushdown";
use super::upsert_dedup;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Unable to create table: {source}"))]
UnableToCreateTable {
source: datafusion::error::DataFusionError,
},
#[snafu(display("Acceleration creation failed: {source}"))]
AccelerationCreationFailed {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[snafu(display("Acceleration initialization failed: {source}"))]
AccelerationInitializationFailed {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[snafu(display(r#"The "duckdb_file" acceleration parameter has an invalid extension. Expected one of "{valid_extensions}" but got "{extension}"."#))]
InvalidFileExtension {
valid_extensions: String,
extension: String,
},
#[snafu(display(r#"The "duckdb_file" acceleration parameter is a directory."#))]
InvalidFileIsDirectory,
#[snafu(display("Acceleration not enabled for dataset: {dataset}"))]
AccelerationNotEnabled { dataset: Arc<str> },
#[snafu(display("Invalid DuckDB acceleration configuration: {detail}"))]
InvalidConfiguration { detail: Arc<str> },
}
type Result<T, E = Error> = std::result::Result<T, E>;
pub struct DuckDBAccelerator {
duckdb_factory: DuckDBTableProviderFactory,
}
impl DuckDBAccelerator {
#[must_use]
pub fn new() -> Self {
Self {
duckdb_factory: create_factory(),
}
}
/// Returns the `DuckDB` file path that would be used for a file-based `DuckDB` accelerator from this dataset
pub fn duckdb_file_path(&self, source: &dyn AccelerationSource) -> Result<String> {
duckdb_file_path(&self.duckdb_factory, source, "accelerated_duckdb")
}
/// Returns an existing `DuckDB` connection pool for the given dataset, or creates a new one if it doesn't exist.
pub async fn get_shared_pool(
&self,
source: &dyn AccelerationSource,
) -> Result<DuckDbConnectionPool> {
let duckdb_file = self.duckdb_file_path(source);
let acceleration = source.acceleration().context(AccelerationNotEnabledSnafu {
dataset: source.name().to_string(),
})?;
let pool = match (duckdb_file, acceleration.mode) {
(Ok(duckdb_file), Mode::File | Mode::FileCreate | Mode::FileUpdate) => {
let num_accelerating_datasets = self.get_num_accelerating_datasets(
Some(duckdb_file.as_str()),
&source.app(),
source.runtime(),
);
let storage =
resolve_acceleration_storage_async(acceleration.storage_profile, &duckdb_file)
.await;
tracing::debug!(
dataset = %source.name(),
storage = %storage,
"Resolved DuckDB acceleration storage profile"
);
let max_size =
Self::get_pool_max_size(num_accelerating_datasets, acceleration, storage);
let min_idle = Self::get_pool_min_idle(storage, max_size);
let mut pool_builder = DuckDbConnectionPoolBuilder::file(&duckdb_file)
.with_max_size(Some(max_size))
.with_min_idle(Some(min_idle))
.with_connection_setup_query("PRAGMA enable_checkpoint_on_shutdown");
for pragma in Self::storage_setup_queries(storage) {
pool_builder = pool_builder.with_connection_setup_query(*pragma);
}
self.duckdb_factory
.get_or_init_instance_with_builder(pool_builder)
.await
.boxed()
.context(AccelerationCreationFailedSnafu)?
}
(_, Mode::Memory) => {
let num_accelerating_datasets =
self.get_num_accelerating_datasets(None, &source.app(), source.runtime());
let max_size = Self::get_pool_max_size(
num_accelerating_datasets,
acceleration,
ResolvedAccelerationStorage::Unknown,
);
let min_idle =
Self::get_pool_min_idle(ResolvedAccelerationStorage::Unknown, max_size);
let pool_builder = DuckDbConnectionPoolBuilder::memory()
.with_max_size(Some(max_size))
.with_min_idle(Some(min_idle))
.with_connection_setup_query("PRAGMA enable_checkpoint_on_shutdown");
self.duckdb_factory
.get_or_init_instance_with_builder(pool_builder)
.await
.boxed()
.context(AccelerationCreationFailedSnafu)?
}
(Err(e), Mode::File | Mode::FileCreate | Mode::FileUpdate) => {
return Err(Error::InvalidConfiguration {
detail: Arc::from(e.to_string()),
});
}
};
Ok(pool)
}
fn get_num_accelerating_datasets(
&self,
path: Option<&str>,
app: &Arc<App>,
rt: Arc<Runtime>,
) -> u32 {
let mut instance_usage: u32 = 1;
let datasets = rt.get_valid_datasets(app, crate::LogErrors(false));
for ds in datasets {
if let Some(acceleration) = &ds.acceleration {
if acceleration.engine != Engine::DuckDB {
continue;
}
// If the path is Some, we're counting the number of file instances
if let Some(this_file_path) = path {
if matches!(
acceleration.mode,
Mode::File | Mode::FileCreate | Mode::FileUpdate
) && let Ok(file_path) = self.file_path(ds.as_ref())
&& this_file_path == file_path
{
instance_usage += 1;
}
} else {
// If the path is None, we're just counting the number of memory instances
if acceleration.mode == Mode::Memory {
instance_usage += 1;
}
}
}
}
instance_usage
}
pub(crate) fn default_connection_pool_size(storage: ResolvedAccelerationStorage) -> u32 {
match storage {
ResolvedAccelerationStorage::Ebs => DEFAULT_EBS_CONNECTION_POOL_SIZE,
ResolvedAccelerationStorage::LocalSsd
| ResolvedAccelerationStorage::Tmpfs
| ResolvedAccelerationStorage::Unknown => DEFAULT_CONNECTION_POOL_SIZE,
}
}
pub(crate) fn get_pool_min_idle(storage: ResolvedAccelerationStorage, max_size: u32) -> u32 {
Self::default_connection_pool_size(storage).min(max_size)
}
/// Storage-profile-specific `DuckDB` pragmas applied to every connection in
/// the pool. These tune `DuckDB`'s I/O behavior to match the underlying
/// medium's latency and durability profile.
pub(crate) fn storage_setup_queries(
storage: ResolvedAccelerationStorage,
) -> &'static [&'static str] {
match storage {
// Network-attached block storage (e.g. EBS, Azure Managed Disks)
// pays per-IO latency on every flush. Raise the checkpoint
// threshold so WAL flushes are larger and less frequent, which
// reduces write amplification on the slow link.
ResolvedAccelerationStorage::Ebs => &["PRAGMA checkpoint_threshold='256MiB'"],
// tmpfs/ramfs is volatile and effectively free to write, but
// checkpointing still copies pages around. Push the threshold up
// so steady-state workloads don't pay checkpoint cost on tiny
// amounts of dirty data.
ResolvedAccelerationStorage::Tmpfs => &["PRAGMA checkpoint_threshold='1GiB'"],
// Local SSD/NVMe handles small frequent flushes well; keep
// DuckDB defaults.
ResolvedAccelerationStorage::LocalSsd | ResolvedAccelerationStorage::Unknown => &[],
}
}
fn get_pool_max_size(
num_accelerating_datasets: u32,
acceleration: &Acceleration,
storage: ResolvedAccelerationStorage,
) -> u32 {
let pool_size_param = acceleration
.params
.get("connection_pool_size")
.and_then(|size_str| size_str.parse::<u32>().ok());
pool_size_param.unwrap_or_else(|| {
max(
Self::default_connection_pool_size(storage),
num_accelerating_datasets,
)
})
}
}
/// Returns the `DuckDB` file path that would be used for a file-based `DuckDB` acceleration for this acceleration source
///
/// # Parameters
///
/// * `duckdb_factory` - The `DuckDB` table provider factory used to generate the file path
/// * `source` - The acceleration source (dataset or view) containing acceleration configuration
/// * `default_db_name` - Default database file name to use if the `duckdb_file` parameter is not specified
pub fn duckdb_file_path(
duckdb_factory: &DuckDBTableProviderFactory,
source: &dyn AccelerationSource,
default_db_name: &str,
) -> Result<String> {
if !source.is_file_accelerated() {
Err(Error::InvalidConfiguration {
detail: Arc::from("Dataset is not file accelerated"),
})
} else if let Some(acceleration) = source.acceleration().as_ref() {
let mut params = acceleration.params.clone();
let mut using_duckdb_data_dir = true;
let data_directory = params.remove("duckdb_data_dir").unwrap_or_else(|| {
using_duckdb_data_dir = false;
spice_data_base_path()
});
params.insert("data_directory".to_string(), data_directory);
if let Some(duckdb_file) = params.remove("duckdb_file") {
if using_duckdb_data_dir {
static WARN_ONCE: Once = Once::new();
WARN_ONCE.call_once(|| {
tracing::warn!(
"'duckdb_data_dir' and 'duckdb_file' were both specified but 'duckdb_file' ({duckdb_file}) will be used."
);
});
}
params.insert("duckdb_open".to_string(), duckdb_file);
}
duckdb_factory
.duckdb_file_path(default_db_name, &mut params)
.map_err(|err| Error::InvalidConfiguration {
detail: Arc::from(err.to_string()),
})
} else {
unreachable!("Expected dataset to have acceleration parameters, but none were found")
}
}
impl Default for DuckDBAccelerator {
fn default() -> Self {
Self::new()
}
}
const PARAMETERS: &[ParameterSpec] = &[
ParameterSpec::runtime("file_watcher"),
ParameterSpec::component("file"),
ParameterSpec::component("data_dir"),
ParameterSpec::component("memory_limit"),
ParameterSpec::component("preserve_insertion_order"),
ParameterSpec::component("index_scan_percentage"),
ParameterSpec::component("index_scan_max_count"),
ParameterSpec::runtime("partition_mode"),
ParameterSpec::component("partitioned_write_flush_threshold_rows"),
ParameterSpec::runtime("connection_pool_size").description(
"The maximum number of client connections created in the duckdb connection pool.",
),
ParameterSpec::runtime("on_refresh_recompute_statistics"),
ParameterSpec::runtime("on_refresh_sort_columns"),
ParameterSpec::runtime("partitioned_write_buffer"),
ParameterSpec::runtime("optimizer_duckdb_aggregate_pushdown"),
];
#[async_trait]
impl DataAccelerator for DuckDBAccelerator {
fn as_any(&self) -> &dyn Any {
self
}
fn name(&self) -> &'static str {
"duckdb"
}
fn valid_file_extensions(&self) -> Vec<&'static str> {
vec!["db", "ddb", "duckdb"]
}
fn file_path(&self, source: &dyn AccelerationSource) -> Result<String, FilePathError> {
self.duckdb_file_path(source)
.map_err(|e| FilePathError::External {
engine: Engine::DuckDB,
source: e.into(),
})
}
fn is_initialized(&self, source: &dyn AccelerationSource) -> bool {
if !source.is_file_accelerated() {
return true; // memory mode DuckDB is always initialized
}
// otherwise, we're initialized if the file exists
self.has_existing_file(source)
}
async fn init(
&self,
source: &dyn AccelerationSource,
) -> Result<BootstrapStatus, Box<dyn std::error::Error + Send + Sync>> {
if !source.is_file_accelerated() {
return Ok(BootstrapStatus::none());
}
let path = self.file_path(source)?;
if let Some(acceleration) = source.acceleration() {
if !acceleration.params.contains_key("duckdb_file") {
make_spice_data_directory().map_err(|err| {
Error::AccelerationInitializationFailed { source: err.into() }
})?;
} else if !self.is_valid_file(source) {
if std::path::Path::new(&path).is_dir() {
return Err(Error::InvalidFileIsDirectory.into());
}
let extension = std::path::Path::new(&path)
.extension()
.and_then(OsStr::to_str)
.unwrap_or("");
return Err(Error::InvalidFileExtension {
valid_extensions: self.valid_file_extensions().join(","),
extension: extension.to_string(),
}
.into());
}
// If mode is FileCreate, snapshot the existing file (if enabled) then delete it to start fresh
if acceleration.mode == Mode::FileCreate {
let file_path = std::path::Path::new(&path);
if file_path.exists() {
snapshot_before_recreate(
acceleration,
&source.name().to_string(),
runtime_acceleration::snapshot::AccelerationLayout::file(PathBuf::from(
&path,
)),
AccelerationEngine::DuckDB,
Arc::new(arrow_schema::Schema::empty()),
None,
)
.await;
tracing::warn!(
"DuckDB acceleration mode is 'file_create', removing existing file: {}",
path
);
std::fs::remove_file(file_path).map_err(|err| {
Error::AccelerationInitializationFailed { source: err.into() }
})?;
}
}
let bootstrap_status = download_snapshot_if_needed(
acceleration,
source,
runtime_acceleration::snapshot::AccelerationLayout::file(PathBuf::from(path)),
AccelerationEngine::DuckDB,
None,
)
.await;
self.get_shared_pool(source).await?;
return Ok(bootstrap_status);
}
Ok(BootstrapStatus::none())
}
/// Creates a new table in the accelerator engine, returning a `TableProvider` that supports reading and writing.
async fn create_external_table(
&self,
mut cmd: CreateExternalTable,
source: Option<&dyn AccelerationSource>,
_partition_by: Vec<PartitionedBy>,
_runtime_env: Option<Arc<RuntimeEnv>>,
) -> Result<Arc<dyn TableProvider>, Box<dyn std::error::Error + Send + Sync>> {
if let Some(duckdb_file) = cmd.options.remove("file") {
cmd.options.insert("open".to_string(), duckdb_file);
}
if let Some(recompute_statistics_on_write) =
cmd.options.remove("on_refresh_recompute_statistics")
{
// Translate Spice parameter to DuckDB write setting
cmd.options.insert(
"recompute_statistics_on_write".to_string(),
recompute_statistics_on_write,
);
}
let is_changes_refresh = source
.and_then(|src| src.acceleration())
.and_then(|acceleration| acceleration.refresh_mode)
.is_some_and(|refresh_mode| refresh_mode == RefreshMode::Changes);
apply_changes_refresh_write_defaults(&mut cmd, is_changes_refresh);
// Modify the `cmd` by adding options to attach other databases
if let Some(source) = source {
if let Some(temp_directory) = source
.app()
.runtime
.query
.clone()
.unwrap_or_default()
.temp_directory
{
cmd.options
.insert("temp_directory".to_string(), temp_directory);
}
if source.is_file_accelerated() {
// If the user didn't specify a DuckDB file and this is a file-mode DuckDB,
// then use the shared DuckDB file `accelerated_duckdb.db`
if !cmd.options.contains_key("open") {
let duckdb_file = self.duckdb_file_path(source)?;
cmd.options.insert("open".to_string(), duckdb_file);
}
let datasets: Vec<Arc<Dataset>> = Arc::clone(&source.runtime())
.get_initialized_datasets(&source.app(), crate::LogErrors(false))
.await;
let views: Vec<Arc<View>> = Arc::clone(&source.runtime())
.get_initialized_views(&source.app(), crate::LogErrors(false))
.await;
let self_path = self.file_path(source)?;
let attach_databases = datasets
.into_iter()
.map(|ds| ds as Arc<dyn AccelerationSource>)
.chain(
views
.into_iter()
.map(|view| view as Arc<dyn AccelerationSource>),
)
.filter_map(|other_source| {
if other_source.acceleration().is_some_and(|a| {
a.engine == Engine::DuckDB
&& matches!(
a.mode,
Mode::File | Mode::FileCreate | Mode::FileUpdate
)
}) {
if other_source.name() == source.name() {
None
} else {
let other_path = self.file_path(other_source.as_ref());
other_path.ok().filter(|p| p != &self_path)
}
} else {
None
}
})
.collect::<HashSet<_>>(); // collect unique paths using HashSet
if !attach_databases.is_empty() {
cmd.options.insert(
"attach_databases".to_string(),
attach_databases.iter().join(";"),
);
}
}
}
let write_completion_handler = source.and_then(|src| {
let acceleration = src.acceleration()?;
let dataset_name = src.name().to_string();
let schema = Arc::new(cmd.schema.as_arrow().clone());
let mut config = OnRefreshConfig::empty();
// Parse retention SQL if configured
if let Some(retention_sql) = acceleration
.retention_sql
.as_deref()
.map(str::trim)
.filter(|sql| !sql.is_empty())
{
match crate::datafusion::retention_sql::parse_retention_sql(
src.name(),
retention_sql,
Arc::clone(&schema),
) {
Ok(parsed_sql) => {
config = config.with_retention(parsed_sql.delete_statement);
}
Err(e) => {
tracing::warn!(
"Failed to parse retention_sql for dataset {dataset_name}: {e}. Retention SQL will not be applied.");
}
}
}
// Parse on_refresh_sort_columns if configured
if let Some(sort_columns_str) = acceleration
.params
.get("on_refresh_sort_columns")
.map(String::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
{
match parse_sort_columns(sort_columns_str, &schema) {
Ok(sort_columns) => {
tracing::debug!(
dataset = %dataset_name,
sort_columns = ?sort_columns,
"Parsed on_refresh_sort_columns"
);
config = config.with_sort(sort_columns);
}
Err(e) => {
tracing::warn!(
"Failed to parse on_refresh_sort_columns for dataset {dataset_name}: {e}. Sorting will not be applied."
);
}
}
}
Some(make_on_refresh_write_handler(dataset_name, config))
});
Ok(create_table_provider(&self.duckdb_factory, &cmd, write_completion_handler).await?)
}
fn prefix(&self) -> &'static str {
"duckdb"
}
fn parameters(&self) -> &'static [ParameterSpec] {
PARAMETERS
}
fn supports_snapshot_reload(&self) -> bool {
true
}
/// Reloads the `DuckDB`-backed table provider from the snapshot file
/// that was just written to the primary path.
///
/// Drops the previous provider, evicts the cached connection pool from
/// the upstream `DuckDBTableProviderFactory` registry, and then re-runs
/// the registry factory to build a fresh provider over the on-disk file.
/// The pool eviction is required because the registry caches pool
/// instances by file path; without it, the freshly built provider would
/// reuse the prior pool's open connections — which keep observing the
/// previous file inode — and queries would continue to return stale data
/// even after the file has been atomically replaced on disk.
async fn reload_from_snapshot(
&self,
source: &dyn AccelerationSource,
previous_provider: Arc<dyn TableProvider>,
provider_factory: super::ReloadProviderFactory,
) -> Result<Arc<dyn TableProvider>, Box<dyn std::error::Error + Send + Sync>> {
// Drop the caller's clone first so the only remaining strong refs to
// the prior pool are the registry entry (which we are about to evict)
// and any in-flight queries (which will drain naturally).
drop(previous_provider);
// Evict the cached pool. For file mode this matches the path the
// factory keyed on at construction time; for memory mode this falls
// back to the in-memory key. Snapshot reload is only meaningful for
// file mode in practice (memory accelerators cannot be snapshotted),
// but the memory branch is kept for completeness.
let acceleration =
source
.acceleration()
.ok_or_else(|| -> Box<dyn std::error::Error + Send + Sync> {
"acceleration not configured for snapshot reload".into()
})?;
match acceleration.mode {
Mode::File | Mode::FileCreate | Mode::FileUpdate => {
let path = self.duckdb_file_path(source).boxed()?;
self.duckdb_factory.invalidate_file_instance(path).await;
}
Mode::Memory => {
self.duckdb_factory
.invalidate_instance(&db_connection_pool::DbInstanceKey::memory())
.await;
}
}
provider_factory().await
}
async fn drop_table(
&self,
table_name: &str,
source: &dyn AccelerationSource,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let pool = Arc::new(self.get_shared_pool(source).await?);
let table_name = table_name.to_owned();
tokio::task::spawn_blocking(
move || -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut conn = pool.connect_sync()?;
let duckdb_conn = DuckDB::duckdb_conn(&mut conn).boxed()?;
let escaped = table_name.replace('"', "\"\"");
let drop_sql = format!("DROP TABLE IF EXISTS \"{escaped}\"");
duckdb_conn
.get_underlying_conn_mut()
.execute(&drop_sql, [])
.boxed()?;
// Also drop any internal DuckDB tables associated with this table
let internal_name = format!("__data_{table_name}").replace('"', "\"\"");
let internal_drop = format!("DROP TABLE IF EXISTS \"{internal_name}\"");
let _ = duckdb_conn
.get_underlying_conn_mut()
.execute(&internal_drop, []);
tracing::info!(
"Dropped DuckDB table '{table_name}' for schema recreation (file_update mode)"
);
Ok(())
},
)
.await
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?
}
}
fn apply_changes_refresh_write_defaults(cmd: &mut CreateExternalTable, is_changes_refresh: bool) {
if is_changes_refresh && !cmd.options.contains_key("recompute_statistics_on_write") {
cmd.options.insert(
"recompute_statistics_on_write".to_string(),
"false".to_string(),
);
}
}
pub(crate) async fn create_table_provider(
duckdb_factory: &DuckDBTableProviderFactory,
cmd: &CreateExternalTable,
on_data_written: Option<WriteCompletionHandler>,
) -> Result<Arc<dyn TableProvider>, Box<dyn std::error::Error + Send + Sync>> {
let ctx = SessionContext::new();
let table_provider = duckdb_factory
.create(&ctx.state(), cmd)
.await
.context(UnableToCreateTableSnafu)
.boxed()?;
let Some(duckdb_writer) = table_provider.as_any().downcast_ref::<DuckDBTableWriter>() else {
unreachable!("DuckDBTableWriter should be returned from DuckDBTableProviderFactory")
};
let read_provider = Arc::clone(&duckdb_writer.read_provider);
let duckdb_writer: Arc<DuckDBTableWriter> = match on_data_written {
Some(handler) => Arc::new(duckdb_writer.clone().with_on_data_written_handler(handler)),
None => Arc::new(duckdb_writer.clone()),
};
// Wrap with upsert deduplication if needed
let write_provider = upsert_dedup::wrap_with_upsert_dedup_if_needed(
duckdb_writer,
&cmd.options,
cmd.constraints.clone(),
);
let mut schema_metadata = HashMap::new();
schema_metadata.insert(
SPICE_ACCELERATOR_METADATA_KEY.to_string(),
"duckdb".to_string(),
);
let agg_pushdown_optimization = cmd
.options
.get("optimizer_duckdb_aggregate_pushdown")
.map_or("disabled", |v| v.as_str())
.to_lowercase();
schema_metadata.insert(
SPICE_OPT_DUCKDB_AGG_PUSHDOWN_KEY.to_string(),
agg_pushdown_optimization,
);
let table_provider = Arc::new(PolyTableProvider::new_with_schema_metadata(
write_provider,
read_provider,
schema_metadata,
));
Ok(table_provider)
}
/// Reconstruct the DELETE statement with the internal `DuckDB` table name.
fn reconstruct_retention_sql_with_table_name(
delete: &Delete,
internal_table_name: &str,
) -> Result<String, String> {
// Clone the delete statement and modify the table name
let mut modified_delete = delete.clone();
// Replace the table name with the internal table name
// DuckDB internal table names should be used as-is without schema qualification
let FromTable::WithFromKeyword(from_tables) = &mut modified_delete.from else {
return Err("DELETE statement must use FROM keyword".to_string());
};
// Replace the first table's name, keeping all other properties
let Some(table_relation) = from_tables.first_mut() else {
return Err("No table specified in DELETE statement".to_string());
};
if let TableFactor::Table { name, .. } = &mut table_relation.relation {
*name = ObjectName(vec![ObjectNamePart::Identifier(Ident::new(
internal_table_name,
))]);
} else {
return Err("DELETE statement must reference a simple table".to_string());
}
// Simply convert the AST to string using Display trait
let statement = SQLStatement::Delete(modified_delete);
Ok(statement.to_string())
}
/// Configuration for on-refresh operations that run after data is written but before commit.
#[derive(Clone, Default)]
struct OnRefreshConfig {
/// Parsed DELETE statement for retention SQL
retention_delete: Option<Delete>,
/// Sort columns configuration
sort_columns: Vec<SortColumn>,
}
impl OnRefreshConfig {
/// Creates an empty config.
fn empty() -> Self {
Self::default()
}
/// Sets retention SQL configuration.
#[must_use]
fn with_retention(mut self, delete: Delete) -> Self {
self.retention_delete = Some(delete);
self
}
/// Sets sort columns configuration.
#[must_use]
fn with_sort(mut self, columns: Vec<SortColumn>) -> Self {
self.sort_columns = columns;
self
}
}
fn make_on_refresh_write_handler(
dataset_name: String,
config: OnRefreshConfig,
) -> WriteCompletionHandler {
Arc::new(move |tx, table_manager, _schema, inserted_rows| {
let internal_table_name = table_manager.table_name().to_string();
// Apply retention SQL if configured
if let Some(ref parsed_delete) = config.retention_delete {
tracing::debug!(
dataset = %dataset_name,
table = %internal_table_name,
inserted_rows,
"Applying retention SQL before commit"
);
let reconstructed_sql = match reconstruct_retention_sql_with_table_name(
parsed_delete,
&internal_table_name,
) {
Ok(sql) => sql,
Err(e) => {
return Err(DataFusionError::Execution(format!(
"Failed to reconstruct retention SQL for dataset {dataset_name}: {e}"
)));
}
};
tracing::debug!(
dataset = %dataset_name,
table = %internal_table_name,
sql = %reconstructed_sql,
"Reconstructed retention SQL with internal table name"
);
match tx.execute(reconstructed_sql.as_str(), []) {
Ok(affected_rows) => {
tracing::debug!(
dataset = %dataset_name,
table = %internal_table_name,
affected_rows,
"Retention SQL applied before commit"
);
}
Err(err) => {
return Err(DataFusionError::Execution(format!(
"Failed to apply retention SQL for dataset {dataset_name} (table {internal_table_name}): {err}"
)));
}
}
}
// Current sorting implementation is experimental. CREATE OR REPLACE TABLE recreates
// the table from scratch, which means:
// - Primary keys and unique constraints (table-level definitions) are NOT preserved
// - Indexes (separate DB objects) are dropped when the original table is replaced
// - Foreign key constraints are NOT preserved
if !config.sort_columns.is_empty() {
let order_by_clause: String = config
.sort_columns
.iter()
.map(|sc| format!("\"{}\" {}", sc.column, sc.direction))
.collect::<Vec<_>>()
.join(", ");
tracing::debug!(
dataset = %dataset_name,
table = %internal_table_name,
inserted_rows,
order_by = %order_by_clause,
"Applying on-refresh sort before commit"
);
let sort_sql = format!(
"CREATE OR REPLACE TABLE \"{internal_table_name}\" AS SELECT * FROM \"{internal_table_name}\" ORDER BY {order_by_clause}"
);
tracing::debug!(
dataset = %dataset_name,
table = %internal_table_name,
sql = %sort_sql,
"Executing on-refresh sort SQL"
);
if let Err(err) = tx.execute(sort_sql.as_str(), []) {
return Err(DataFusionError::Execution(format!(
"Failed to apply on-refresh sort for dataset {dataset_name} (table {internal_table_name}): {err}"
)));
}
tracing::debug!(
dataset = %dataset_name,
table = %internal_table_name,
"On-refresh sort applied before commit"
);
}
table_manager.create_indexes(tx).map_err(|err| {
DataFusionError::Execution(format!(
"Failed to create DuckDB indexes for dataset {dataset_name} (table {internal_table_name}) before refresh commit: {err}"
))
})?;
Ok(())
})
}
register_data_accelerator!(Engine::DuckDB, DuckDBAccelerator);
#[cfg(test)]
mod tests {
use std::{collections::HashMap, sync::Arc};
use crate::component::dataset::builder::DatasetBuilder;
use arrow::{
array::{Int64Array, RecordBatch, StringArray, TimestampSecondArray, UInt64Array},
datatypes::{DataType, Field, Schema},
};
use datafusion::{
common::{Constraints, TableReference, ToDFSchema},
execution::context::SessionContext,
logical_expr::{CreateExternalTable, cast, col, dml::InsertOp, lit},