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
//! The analysis selection every parser and engine must honour.
//!
//! Metric packs, quality dimensions, locale, and semantic hints are all
//! *requests about what to compute*, and the report they produce has to be the
//! same on every input path. Passing them as loose parameters made that easy to
//! get wrong: a parser that took dimensions and hints but not packs or locale
//! compiled fine and silently computed work the caller had deselected.
//! [`AnalysisOptions`] bundles them so a path either carries the whole selection
//! or does not compile.
use std::collections::HashSet;
use chrono::NaiveDate;
use crate::errors::DataProfilerError;
use crate::locale::Locale;
use crate::quality::{MetricPack, QualityDimension};
use crate::semantic::SemanticHints;
/// What to analyze, and how, for a single profiling run.
///
/// Construct with [`AnalysisOptions::default`] (analyze everything) and narrow
/// with the builder methods.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AnalysisOptions {
columns: Option<Vec<String>>,
metric_packs: Option<Vec<MetricPack>>,
quality_dimensions: Option<Vec<QualityDimension>>,
locale: Option<Locale>,
semantic_hints: SemanticHints,
reference_date: Option<NaiveDate>,
duplicate_rows_exact_limit: Option<usize>,
}
impl AnalysisOptions {
/// Select top-level columns to profile. `None` (the default) means every column.
///
/// Selection is by name and reports remain in source-schema order. An empty
/// vector requests a schema with no profiled columns.
pub fn with_columns(mut self, columns: Option<Vec<String>>) -> Self {
self.columns = columns;
self
}
/// Select the metric packs to compute. `None` (the default) means all.
pub fn with_metric_packs(mut self, packs: Option<Vec<MetricPack>>) -> Self {
self.metric_packs = packs;
self
}
/// Select the quality dimensions to assess. `None` (the default) means all.
pub fn with_quality_dimensions(mut self, dimensions: Option<Vec<QualityDimension>>) -> Self {
self.quality_dimensions = dimensions;
self
}
/// Set the locale used to rank detected patterns.
///
/// Parse a user-supplied tag with [`Locale::parse_optional`] first, so an
/// unrecognised tag is rejected where it is written rather than silently
/// suppressing every locale-specific pattern.
pub fn with_locale(mut self, locale: Option<Locale>) -> Self {
self.locale = locale;
self
}
/// Set the user's semantic hints.
pub fn with_semantic_hints(mut self, hints: SemanticHints) -> Self {
self.semantic_hints = hints;
self
}
/// Fix the date timeliness measures against. `None` (the default) reads
/// today's UTC date when the run starts, so an unchanged file's timeliness
/// moves as the calendar does; a fixed date makes it reproducible (#903).
/// The report records which one the score used.
pub fn with_reference_date(mut self, reference_date: Option<NaiveDate>) -> Self {
self.reference_date = reference_date;
self
}
/// Count duplicate rows exactly up to `limit` distinct rows (#1292).
///
/// `None` (the default) keeps the built-in limit of one million distinct
/// rows, past which the count is an estimate and the memory budget may
/// end the exact count earlier. A limit set here is a row count, so the
/// verdict does not depend on the machine: the row tracker keeps its exact
/// set up to the limit whatever `memory_limit_mb` says, at 10 to 20 bytes
/// per distinct row, and that set is not counted against the budget.
pub fn with_duplicate_rows_exact_limit(mut self, limit: Option<usize>) -> Self {
self.duplicate_rows_exact_limit = limit;
self
}
/// The packs to compute, with an empty quality-dimension selection folded in.
///
/// Resolved on read rather than in the setters so the outcome does not
/// depend on the order the selections were made in.
pub fn effective_metric_packs(&self) -> Option<Vec<MetricPack>> {
MetricPack::resolve_with_dimensions(
self.metric_packs.as_deref(),
self.quality_dimensions.as_deref(),
)
}
/// Every pack the run computes, in [`MetricPack::all`] order: the
/// effective selection with the schema pack, which is always computed,
/// made explicit. Two requests that compute the same packs return the
/// same list, whatever order or repetition they were given in.
pub fn selected_metric_packs(&self) -> Vec<MetricPack> {
let effective = self.effective_metric_packs();
MetricPack::all()
.into_iter()
.filter(|pack| {
*pack == MetricPack::Schema
|| effective
.as_deref()
.is_none_or(|selected| selected.contains(pack))
})
.collect()
}
/// Whether per-column statistics should be computed.
pub fn include_statistics(&self) -> bool {
MetricPack::include_statistics(self.effective_metric_packs().as_deref())
}
/// Whether pattern detection should run.
pub fn include_patterns(&self) -> bool {
MetricPack::include_patterns(self.effective_metric_packs().as_deref())
}
/// Whether quality metrics should be computed.
///
/// `false` means the report carries no quality at all — absent, not an
/// empty assessment — because nothing was analyzed.
pub fn include_quality(&self) -> bool {
MetricPack::include_quality(self.effective_metric_packs().as_deref())
}
/// The locale used to rank detected patterns.
///
/// A locale only ranks patterns, so it has no effect of its own when
/// [`include_patterns`](Self::include_patterns) is false and detection never
/// runs.
pub fn locale(&self) -> Option<Locale> {
self.locale
}
/// The fixed timeliness reference date, or `None` to read today's.
pub fn reference_date(&self) -> Option<NaiveDate> {
self.reference_date
}
/// The duplicate-row exact limit the caller set, or `None` for the default.
pub fn duplicate_rows_exact_limit(&self) -> Option<usize> {
self.duplicate_rows_exact_limit
}
/// The requested quality dimensions, if the caller narrowed them.
pub fn quality_dimensions(&self) -> Option<&[QualityDimension]> {
self.quality_dimensions.as_deref()
}
/// The user's semantic hints.
pub fn semantic_hints(&self) -> &SemanticHints {
&self.semantic_hints
}
/// The requested top-level column names, or `None` when every column is selected.
pub fn columns(&self) -> Option<&[String]> {
self.columns.as_deref()
}
/// Whether the caller selected a subset of the source columns.
pub fn has_column_projection(&self) -> bool {
self.columns.is_some()
}
/// Resolve the selected columns against a source schema.
///
/// Returned indices follow source order, not request order, so every input
/// path preserves the same stable report ordering. Unknown and duplicate
/// requests fail rather than producing a plausible partial profile.
pub fn column_indices(
&self,
available: &[String],
) -> Result<Option<Vec<usize>>, DataProfilerError> {
let Some(requested) = &self.columns else {
return Ok(None);
};
let mut seen = HashSet::with_capacity(requested.len());
let duplicates = requested
.iter()
.filter(|name| !seen.insert(name.as_str()))
.cloned()
.collect::<Vec<_>>();
if !duplicates.is_empty() {
return Err(DataProfilerError::invalid_config(
&format!(
"column projection contains duplicate name(s): {}",
duplicates.join(", ")
),
"List each projected column once.",
));
}
let available_set = available.iter().map(String::as_str).collect::<HashSet<_>>();
let missing = requested
.iter()
.filter(|name| !available_set.contains(name.as_str()))
.cloned()
.collect::<Vec<_>>();
if !missing.is_empty() {
return Err(DataProfilerError::invalid_config(
&format!(
"column projection names column(s) absent from the source: {}",
missing.join(", ")
),
"Choose column names from the source schema.",
));
}
Ok(Some(
available
.iter()
.enumerate()
.filter_map(|(index, name)| seen.contains(name.as_str()).then_some(index))
.collect(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_analyzes_everything() {
let options = AnalysisOptions::default();
assert!(options.include_statistics());
assert!(options.include_patterns());
assert!(options.include_quality());
assert_eq!(options.locale(), None);
assert_eq!(options.quality_dimensions(), None);
assert_eq!(options.columns(), None);
assert!(!options.has_column_projection());
}
#[test]
fn schema_only_deselects_every_other_pack() {
let options = AnalysisOptions::default().with_metric_packs(Some(vec![MetricPack::Schema]));
assert!(!options.include_statistics());
assert!(!options.include_patterns());
assert!(!options.include_quality());
}
#[test]
fn empty_dimension_selection_removes_the_quality_pack() {
let options = AnalysisOptions::default().with_quality_dimensions(Some(vec![]));
assert!(!options.include_quality());
// Deselecting quality says nothing about the other packs.
assert!(options.include_statistics());
assert!(options.include_patterns());
}
#[test]
fn resolution_does_not_depend_on_setter_order() {
let packs = vec![MetricPack::Schema, MetricPack::Quality];
let dims_first = AnalysisOptions::default()
.with_quality_dimensions(Some(vec![]))
.with_metric_packs(Some(packs.clone()));
let packs_first = AnalysisOptions::default()
.with_metric_packs(Some(packs))
.with_quality_dimensions(Some(vec![]));
assert_eq!(
dims_first.effective_metric_packs(),
packs_first.effective_metric_packs()
);
assert!(!dims_first.include_quality());
}
#[test]
fn selected_packs_list_what_runs_once_in_a_fixed_order() {
use MetricPack::{Patterns, Quality, Schema, Statistics};
let selected = |options: AnalysisOptions| options.selected_metric_packs();
assert_eq!(
selected(AnalysisOptions::default()),
vec![Schema, Statistics, Patterns, Quality]
);
assert_eq!(
selected(
AnalysisOptions::default()
.with_metric_packs(Some(vec![Quality, Patterns, Quality]))
),
vec![Schema, Patterns, Quality]
);
assert_eq!(
selected(AnalysisOptions::default().with_metric_packs(Some(vec![]))),
vec![Schema]
);
assert_eq!(
selected(AnalysisOptions::default().with_quality_dimensions(Some(vec![]))),
vec![Schema, Statistics, Patterns]
);
}
#[test]
fn a_locale_alone_does_not_re_enable_pattern_detection() {
let options = AnalysisOptions::default()
.with_locale(Some(Locale::It))
.with_metric_packs(Some(vec![MetricPack::Schema]));
assert_eq!(options.locale(), Some(Locale::It));
assert!(!options.include_patterns());
}
#[test]
fn column_projection_resolves_in_source_order() {
let options = AnalysisOptions::default()
.with_columns(Some(vec!["city".to_string(), "id".to_string()]));
let available = vec!["id".to_string(), "name".to_string(), "city".to_string()];
assert_eq!(
options.column_indices(&available).unwrap(),
Some(vec![0, 2])
);
assert!(options.has_column_projection());
}
#[test]
fn column_projection_rejects_unknown_and_duplicate_names() {
let available = vec!["id".to_string(), "city".to_string()];
let unknown = AnalysisOptions::default().with_columns(Some(vec!["name".to_string()]));
assert!(unknown.column_indices(&available).is_err());
let duplicate =
AnalysisOptions::default().with_columns(Some(vec!["id".to_string(), "id".to_string()]));
assert!(duplicate.column_indices(&available).is_err());
}
}