delta-funnel 0.5.0

Lightweight, fast Delta Lake to SQL Server loads with DataFusion SQL and native TDS
Documentation
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
use std::fmt;

use crate::{
    ExecutionProfileMode, MssqlTargetConfig, MssqlTargetOutputPlan, PhaseTimingReport,
    QueryExecutionProfile, ReportReasonCode, ResolvedMssqlTarget,
    support::sanitize_text_for_display,
};

pub(crate) const PREVIEW_DATAFRAME_PLANNING_PHASE: &str = "preview_dataframe_planning";
pub(crate) const PREVIEW_PHYSICAL_PLANNING_PHASE: &str = "preview_physical_planning";
pub(crate) const PREVIEW_STREAM_SETUP_PHASE: &str = "preview_stream_setup";
pub(crate) const PREVIEW_EXECUTE_COLLECT_PHASE: &str = "preview_execute_collect";
pub(crate) const PREVIEW_FORMAT_TEXT_PHASE: &str = "preview_format_text";
pub(crate) const PREVIEW_FORMAT_HTML_PHASE: &str = "preview_format_html";
pub(crate) const PREVIEW_TOTAL_PHASE: &str = "preview_total";

pub(crate) const PREVIEW_PHASE_NAMES: [&str; 7] = [
    PREVIEW_DATAFRAME_PLANNING_PHASE,
    PREVIEW_PHYSICAL_PLANNING_PHASE,
    PREVIEW_STREAM_SETUP_PHASE,
    PREVIEW_EXECUTE_COLLECT_PHASE,
    PREVIEW_FORMAT_TEXT_PHASE,
    PREVIEW_FORMAT_HTML_PHASE,
    PREVIEW_TOTAL_PHASE,
];

/// Query-load action mode requested by a caller.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RunMode {
    /// Plan and execute the selected output workflow.
    #[default]
    Execute,
    /// Reuse planning paths without row production or SQL Server write effects.
    DryRun,
}

/// Lazy table identity owned by a query-load session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LazyTable {
    id: LazyTableId,
    kind: LazyTableKind,
    name: String,
}

impl LazyTable {
    /// Creates a placeholder lazy table handle for future registration slices.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn placeholder(id: u64, kind: LazyTableKind) -> Self {
        Self {
            id: LazyTableId(id),
            kind,
            name: format!("table_{id}"),
        }
    }

    pub(super) fn delta_source(id: u64, name: String) -> Self {
        Self {
            id: LazyTableId(id),
            kind: LazyTableKind::DeltaSource,
            name,
        }
    }

    pub(super) fn derived_sql(id: u64) -> Self {
        Self {
            id: LazyTableId(id),
            kind: LazyTableKind::DerivedSql,
            name: format!("table_{id}"),
        }
    }

    pub(super) fn with_name(&self, name: String) -> Self {
        Self {
            id: self.id,
            kind: self.kind,
            name,
        }
    }

    /// Returns the stable session-local table id.
    #[must_use]
    pub const fn id(&self) -> u64 {
        self.id.0
    }

    /// Returns the lazy table kind.
    #[must_use]
    pub const fn kind(&self) -> LazyTableKind {
        self.kind
    }

    /// Returns the session-owned table name for this lazy table.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct LazyTableId(u64);

/// Kind of lazy table represented by a session handle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LazyTableKind {
    /// Registered Delta source table.
    DeltaSource,
    /// SQL-derived table.
    DerivedSql,
}

/// Options for a bounded lazy-table preview.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PreviewOptions {
    limit: usize,
    execution_profile_mode: ExecutionProfileMode,
}

impl PreviewOptions {
    /// Creates preview options with detailed execution profiling disabled.
    #[must_use]
    pub const fn new(limit: usize) -> Self {
        Self {
            limit,
            execution_profile_mode: ExecutionProfileMode::Disabled,
        }
    }

    /// Selects whether the preview collects a detailed execution profile.
    #[must_use]
    pub const fn with_execution_profile_mode(mut self, mode: ExecutionProfileMode) -> Self {
        self.execution_profile_mode = mode;
        self
    }

    /// Returns the requested preview row limit.
    #[must_use]
    pub const fn limit(&self) -> usize {
        self.limit
    }

    /// Returns the selected execution-profile mode.
    #[must_use]
    pub const fn execution_profile_mode(&self) -> ExecutionProfileMode {
        self.execution_profile_mode
    }
}

/// Structured diagnostics retained when a bounded preview fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreviewFailureContext {
    failed_phase: String,
    phase_timings: Vec<PhaseTimingReport>,
    execution_profile: Option<QueryExecutionProfile>,
}

impl PreviewFailureContext {
    pub(crate) fn new(
        failed_phase: String,
        phase_timings: Vec<PhaseTimingReport>,
        execution_profile: Option<QueryExecutionProfile>,
    ) -> Self {
        Self {
            failed_phase,
            phase_timings,
            execution_profile,
        }
    }

    /// Returns the stable name of the phase that failed.
    #[must_use]
    pub fn failed_phase(&self) -> &str {
        &self.failed_phase
    }

    /// Returns the complete ordered preview phase timings.
    #[must_use]
    pub fn phase_timings(&self) -> &[PhaseTimingReport] {
        &self.phase_timings
    }

    /// Returns the terminal execution profile when detailed profiling reached
    /// a terminal transition, including stream-setup failure.
    #[must_use]
    pub const fn execution_profile(&self) -> Option<&QueryExecutionProfile> {
        self.execution_profile.as_ref()
    }
}

/// Rendered bounded preview of a lazy table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TablePreview {
    text: String,
    html: String,
    phase_timings: Vec<PhaseTimingReport>,
    execution_profile: Option<QueryExecutionProfile>,
}

impl TablePreview {
    /// Creates a rendered lazy table preview without execution diagnostics.
    ///
    /// All seven preview phase timings are marked unavailable with
    /// [`ReportReasonCode::NotExecuted`], and no execution profile is attached.
    #[must_use]
    pub fn new(text: String, html: String) -> Self {
        Self::from_execution(
            text,
            html,
            PREVIEW_PHASE_NAMES
                .into_iter()
                .map(|phase_name| {
                    PhaseTimingReport::unavailable(phase_name, ReportReasonCode::NotExecuted)
                })
                .collect(),
            None,
        )
    }

    pub(crate) fn from_execution(
        text: String,
        html: String,
        phase_timings: Vec<PhaseTimingReport>,
        execution_profile: Option<QueryExecutionProfile>,
    ) -> Self {
        Self {
            text,
            html,
            phase_timings,
            execution_profile,
        }
    }

    /// Returns the plain text table preview.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the HTML table preview.
    #[must_use]
    pub fn html(&self) -> &str {
        &self.html
    }

    /// Returns phase timings captured for this preview operation.
    #[must_use]
    pub fn phase_timings(&self) -> &[PhaseTimingReport] {
        &self.phase_timings
    }

    /// Returns the detailed execution profile when collection was enabled.
    #[must_use]
    pub const fn execution_profile(&self) -> Option<&QueryExecutionProfile> {
        self.execution_profile.as_ref()
    }
}

/// MSSQL output target selected from a lazy table.
#[derive(Clone, PartialEq, Eq)]
pub struct MssqlOutputTarget {
    output_name: String,
    target: MssqlTargetConfig,
    run_mode: RunMode,
}

impl MssqlOutputTarget {
    /// Creates an MSSQL output target request.
    #[must_use]
    pub fn new(
        output_name: impl Into<String>,
        target: MssqlTargetConfig,
        run_mode: RunMode,
    ) -> Self {
        Self {
            output_name: output_name.into(),
            target,
            run_mode,
        }
    }

    /// Returns the selected output name.
    #[must_use]
    pub fn output_name(&self) -> &str {
        &self.output_name
    }

    /// Returns the SQL Server target config.
    #[must_use]
    pub const fn target(&self) -> &MssqlTargetConfig {
        &self.target
    }

    /// Returns the requested run mode.
    #[must_use]
    pub const fn run_mode(&self) -> RunMode {
        self.run_mode
    }
}

impl fmt::Debug for MssqlOutputTarget {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MssqlOutputTarget")
            .field("output_name", &sanitize_text_for_display(&self.output_name))
            .field("target", &self.target)
            .field("run_mode", &self.run_mode)
            .finish()
    }
}

/// Planned output write request before schema planning or execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutputWritePlan {
    table: LazyTable,
    target: MssqlOutputTarget,
}

impl OutputWritePlan {
    /// Creates an output write request for a lazy table.
    #[must_use]
    pub const fn new(table: LazyTable, target: MssqlOutputTarget) -> Self {
        Self { table, target }
    }

    /// Returns the selected lazy table.
    #[must_use]
    pub const fn table(&self) -> &LazyTable {
        &self.table
    }

    /// Returns the selected MSSQL output target.
    #[must_use]
    pub const fn target(&self) -> &MssqlOutputTarget {
        &self.target
    }
}

/// Planned MSSQL output request for one selected lazy table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlannedMssqlOutput {
    request: OutputWritePlan,
    resolved_target: ResolvedMssqlTarget,
    output_plan: MssqlTargetOutputPlan,
    phase_timings: Vec<PhaseTimingReport>,
}

impl PlannedMssqlOutput {
    pub(super) fn new(
        request: OutputWritePlan,
        resolved_target: ResolvedMssqlTarget,
        output_plan: MssqlTargetOutputPlan,
        phase_timings: Vec<PhaseTimingReport>,
    ) -> Self {
        Self {
            request,
            resolved_target,
            output_plan,
            phase_timings,
        }
    }

    /// Returns the original lazy-table output request.
    #[must_use]
    pub const fn request(&self) -> &OutputWritePlan {
        &self.request
    }

    /// Returns the selected lazy table.
    #[must_use]
    pub const fn table(&self) -> &LazyTable {
        self.request.table()
    }

    /// Returns the selected MSSQL target request.
    #[must_use]
    pub const fn target(&self) -> &MssqlOutputTarget {
        self.request.target()
    }

    /// Returns the resolved SQL Server target, including the private connection config.
    #[must_use]
    pub const fn resolved_target(&self) -> &ResolvedMssqlTarget {
        &self.resolved_target
    }

    /// Returns the complete SQL Server target output plan.
    #[must_use]
    pub const fn output_plan(&self) -> &MssqlTargetOutputPlan {
        &self.output_plan
    }

    /// Returns durable phase timings captured while planning this output.
    #[must_use]
    pub fn phase_timings(&self) -> &[PhaseTimingReport] {
        &self.phase_timings
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        DeltaFunnelError, ExecutionProfileMode, LoadMode, MssqlConnectionConfig, MssqlTargetConfig,
        MssqlTargetTable, PhaseStatus, ReportReasonCode,
    };

    use super::{
        LazyTable, LazyTableKind, MssqlOutputTarget, OutputWritePlan, PREVIEW_PHASE_NAMES,
        PreviewOptions, RunMode, TablePreview,
    };

    #[test]
    fn preview_options_default_to_disabled_profiling() {
        let default = PreviewOptions::new(20);
        let detailed = default.with_execution_profile_mode(ExecutionProfileMode::Detailed);

        assert_eq!(default.limit(), 20);
        assert_eq!(
            default.execution_profile_mode(),
            ExecutionProfileMode::Disabled
        );
        assert_eq!(detailed.limit(), 20);
        assert_eq!(
            detailed.execution_profile_mode(),
            ExecutionProfileMode::Detailed
        );
    }

    #[test]
    fn legacy_table_preview_has_unavailable_timings_and_no_profile() {
        let preview = TablePreview::new("text".to_owned(), "html".to_owned());

        assert_eq!(preview.text(), "text");
        assert_eq!(preview.html(), "html");
        assert_eq!(preview.phase_timings().len(), PREVIEW_PHASE_NAMES.len());
        for (timing, phase_name) in preview.phase_timings().iter().zip(PREVIEW_PHASE_NAMES) {
            assert_eq!(timing.phase_name(), phase_name);
            assert_eq!(
                timing.status(),
                PhaseStatus::unavailable(ReportReasonCode::NotExecuted)
            );
            assert_eq!(timing.elapsed_micros(), None);
        }
        assert_eq!(preview.execution_profile(), None);
    }

    #[test]
    fn output_request_shapes_preserve_table_target_and_run_mode() -> Result<(), DeltaFunnelError> {
        let table = LazyTable::placeholder(7, LazyTableKind::DerivedSql);
        let target_config = MssqlTargetConfig::new(MssqlTargetTable::new("dbo", "orders")?)
            .with_load_mode(LoadMode::CreateAndLoad)
            .with_connection(
                MssqlConnectionConfig::new(
                    "server=tcp:sql.example.com;database=warehouse;user=admin;password=secret-token",
                )?
                .with_display_label("warehouse-primary"),
            );
        let target = MssqlOutputTarget::new("orders_output", target_config, RunMode::DryRun);
        let plan = OutputWritePlan::new(table.clone(), target.clone());

        assert_eq!(table.id(), 7);
        assert_eq!(table.kind(), LazyTableKind::DerivedSql);
        assert_eq!(target.output_name(), "orders_output");
        assert_eq!(target.run_mode(), RunMode::DryRun);
        assert_eq!(target.target().load_mode(), LoadMode::CreateAndLoad);
        assert_eq!(plan.table(), &table);
        assert_eq!(plan.target(), &target);

        let debug = format!("{target:?}");
        assert!(debug.contains("orders_output"));
        assert!(!debug.contains("secret-token"));
        assert!(!debug.contains("password"));
        assert!(!debug.contains("server=tcp"));
        Ok(())
    }
}