1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4use polars::chunked_array::cast::CastOptions;
5use polars::prelude::{Column, DataFrame, DataType, NamedFrom, Schema, Series};
6
7use crate::io::storage::Target;
8use crate::{check, config, io, ConfigError, FloeResult};
9
10#[derive(Debug, Clone)]
11pub struct InputFile {
12 pub source_uri: String,
13 pub source_local_path: PathBuf,
14 pub source_name: String,
15 pub source_stem: String,
16}
17
18#[derive(Debug, Clone)]
19pub struct FileReadError {
20 pub rule: String,
21 pub message: String,
22}
23
24pub enum ReadInput {
25 Data {
26 input_file: InputFile,
27 raw_df: Option<DataFrame>,
28 typed_df: DataFrame,
29 },
30 FileError {
31 input_file: InputFile,
32 error: FileReadError,
33 },
34}
35
36#[derive(Debug, Clone)]
37pub struct AcceptedWriteOutput {
38 pub parts_written: u64,
39 pub part_files: Vec<String>,
40 pub table_version: Option<i64>,
41}
42
43pub trait InputAdapter: Send + Sync {
44 fn format(&self) -> &'static str;
45
46 fn default_globs(&self) -> FloeResult<Vec<String>> {
47 io::storage::extensions::glob_patterns_for_format(self.format())
48 }
49
50 fn suffixes(&self) -> FloeResult<Vec<String>> {
51 io::storage::extensions::suffixes_for_format(self.format())
52 }
53
54 fn resolve_local_inputs(
55 &self,
56 config_dir: &Path,
57 entity_name: &str,
58 source: &config::SourceConfig,
59 storage: &str,
60 ) -> FloeResult<io::storage::local::ResolvedLocalInputs> {
61 let default_globs = self.default_globs()?;
62 io::storage::local::resolve_local_inputs(
63 config_dir,
64 entity_name,
65 source,
66 storage,
67 &default_globs,
68 )
69 }
70
71 fn read_input_columns(
72 &self,
73 entity: &config::EntityConfig,
74 input_file: &InputFile,
75 columns: &[config::ColumnConfig],
76 ) -> Result<Vec<String>, FileReadError>;
77
78 fn read_inputs(
79 &self,
80 entity: &config::EntityConfig,
81 files: &[InputFile],
82 columns: &[config::ColumnConfig],
83 normalize_strategy: Option<&str>,
84 collect_raw: bool,
85 ) -> FloeResult<Vec<ReadInput>>;
86}
87
88pub trait AcceptedSinkAdapter: Send + Sync {
89 #[allow(clippy::too_many_arguments)]
90 fn write_accepted(
91 &self,
92 target: &Target,
93 df: &mut DataFrame,
94 mode: config::WriteMode,
95 output_stem: &str,
96 temp_dir: Option<&Path>,
97 cloud: &mut io::storage::CloudClient,
98 resolver: &config::StorageResolver,
99 entity: &config::EntityConfig,
100 ) -> FloeResult<AcceptedWriteOutput>;
101}
102
103pub struct RejectedWriteRequest<'a> {
104 pub target: &'a Target,
105 pub df: &'a mut DataFrame,
106 pub source_stem: &'a str,
107 pub temp_dir: Option<&'a Path>,
108 pub cloud: &'a mut io::storage::CloudClient,
109 pub resolver: &'a config::StorageResolver,
110 pub entity: &'a config::EntityConfig,
111 pub mode: config::WriteMode,
112}
113
114pub trait RejectedSinkAdapter: Send + Sync {
115 fn write_rejected(&self, request: RejectedWriteRequest<'_>) -> FloeResult<String>;
116}
117
118#[derive(Debug, Clone, Copy)]
119pub enum FormatKind {
120 Source,
121 SinkAccepted,
122 SinkRejected,
123}
124
125impl FormatKind {
126 fn field_path(self) -> &'static str {
127 match self {
128 FormatKind::Source => "source.format",
129 FormatKind::SinkAccepted => "sink.accepted.format",
130 FormatKind::SinkRejected => "sink.rejected.format",
131 }
132 }
133
134 fn description(self) -> &'static str {
135 match self {
136 FormatKind::Source => "source format",
137 FormatKind::SinkAccepted => "accepted sink format",
138 FormatKind::SinkRejected => "rejected sink format",
139 }
140 }
141}
142
143fn unsupported_format_error(
144 kind: FormatKind,
145 format: &str,
146 entity_name: Option<&str>,
147) -> ConfigError {
148 if let Some(entity_name) = entity_name {
149 return ConfigError(format!(
150 "entity.name={} {}={} is unsupported",
151 entity_name,
152 kind.field_path(),
153 format
154 ));
155 }
156 ConfigError(format!("unsupported {}: {format}", kind.description()))
157}
158
159pub fn ensure_input_format(entity_name: &str, format: &str) -> FloeResult<()> {
160 if input_adapter(format).is_err() {
161 return Err(Box::new(unsupported_format_error(
162 FormatKind::Source,
163 format,
164 Some(entity_name),
165 )));
166 }
167 Ok(())
168}
169
170pub fn ensure_accepted_sink_format(entity_name: &str, format: &str) -> FloeResult<()> {
171 if accepted_sink_adapter(format).is_err() {
172 return Err(Box::new(unsupported_format_error(
173 FormatKind::SinkAccepted,
174 format,
175 Some(entity_name),
176 )));
177 }
178 Ok(())
179}
180
181pub fn ensure_rejected_sink_format(entity_name: &str, format: &str) -> FloeResult<()> {
182 if rejected_sink_adapter(format).is_err() {
183 return Err(Box::new(unsupported_format_error(
184 FormatKind::SinkRejected,
185 format,
186 Some(entity_name),
187 )));
188 }
189 Ok(())
190}
191
192pub fn sink_options_warning(
193 entity_name: &str,
194 format: &str,
195 options: Option<&config::SinkOptions>,
196) -> Option<String> {
197 let options = options?;
198 if format == "parquet" {
199 return None;
200 }
201 let mut keys = Vec::new();
202 if options.compression.is_some() {
203 keys.push("compression");
204 }
205 if options.row_group_size.is_some() {
206 keys.push("row_group_size");
207 }
208 if options.max_size_per_file.is_some() {
209 keys.push("max_size_per_file");
210 }
211 let detail = if keys.is_empty() {
212 "options".to_string()
213 } else {
214 keys.join(", ")
215 };
216 Some(format!(
217 "entity.name={} sink.accepted.options ({detail}) ignored for format={}",
218 entity_name, format
219 ))
220}
221
222pub fn validate_sink_options(
223 entity_name: &str,
224 format: &str,
225 options: Option<&config::SinkOptions>,
226) -> FloeResult<()> {
227 let options = match options {
228 Some(options) => options,
229 None => return Ok(()),
230 };
231 if format != "parquet" {
232 return Ok(());
233 }
234 if let Some(compression) = &options.compression {
235 match compression.as_str() {
236 "snappy" | "gzip" | "zstd" | "uncompressed" => {}
237 _ => {
238 return Err(Box::new(ConfigError(format!(
239 "entity.name={} sink.accepted.options.compression={} is unsupported (allowed: snappy, gzip, zstd, uncompressed)",
240 entity_name, compression
241 ))))
242 }
243 }
244 }
245 if let Some(row_group_size) = options.row_group_size {
246 if row_group_size == 0 {
247 return Err(Box::new(ConfigError(format!(
248 "entity.name={} sink.accepted.options.row_group_size must be greater than 0",
249 entity_name
250 ))));
251 }
252 }
253 if let Some(max_size_per_file) = options.max_size_per_file {
254 if max_size_per_file == 0 {
255 return Err(Box::new(ConfigError(format!(
256 "entity.name={} sink.accepted.options.max_size_per_file must be greater than 0",
257 entity_name
258 ))));
259 }
260 }
261 Ok(())
262}
263
264pub fn input_adapter(format: &str) -> FloeResult<&'static dyn InputAdapter> {
265 match format {
266 "csv" => Ok(io::read::csv::csv_input_adapter()),
267 "parquet" => Ok(io::read::parquet::parquet_input_adapter()),
268 "json" => Ok(io::read::json::json_input_adapter()),
269 _ => Err(Box::new(unsupported_format_error(
270 FormatKind::Source,
271 format,
272 None,
273 ))),
274 }
275}
276
277pub fn accepted_sink_adapter(format: &str) -> FloeResult<&'static dyn AcceptedSinkAdapter> {
278 match format {
279 "parquet" => Ok(io::write::parquet::parquet_accepted_adapter()),
280 "delta" => Ok(io::write::delta::delta_accepted_adapter()),
281 "iceberg" => Ok(io::write::iceberg::iceberg_accepted_adapter()),
282 _ => Err(Box::new(unsupported_format_error(
283 FormatKind::SinkAccepted,
284 format,
285 None,
286 ))),
287 }
288}
289
290pub fn rejected_sink_adapter(format: &str) -> FloeResult<&'static dyn RejectedSinkAdapter> {
291 match format {
292 "csv" => Ok(io::write::csv::csv_rejected_adapter()),
293 _ => Err(Box::new(unsupported_format_error(
294 FormatKind::SinkRejected,
295 format,
296 None,
297 ))),
298 }
299}
300
301pub(crate) fn read_input_from_df(
302 input_file: &InputFile,
303 df: &DataFrame,
304 columns: &[config::ColumnConfig],
305 normalize_strategy: Option<&str>,
306 collect_raw: bool,
307) -> FloeResult<ReadInput> {
308 let input_columns = df
309 .get_column_names()
310 .iter()
311 .map(|name| name.to_string())
312 .collect::<Vec<_>>();
313 let typed_schema = build_typed_schema(&input_columns, columns, normalize_strategy)?;
314 let raw_df = if collect_raw {
315 Some(cast_df_to_string(df)?)
316 } else {
317 None
318 };
319 let typed_df = cast_df_to_schema(df, &typed_schema)?;
320 finalize_read_input(input_file, raw_df, typed_df, normalize_strategy)
321}
322
323pub(crate) fn finalize_read_input(
324 input_file: &InputFile,
325 mut raw_df: Option<DataFrame>,
326 mut typed_df: DataFrame,
327 normalize_strategy: Option<&str>,
328) -> FloeResult<ReadInput> {
329 if let Some(strategy) = normalize_strategy {
330 if let Some(raw_df) = raw_df.as_mut() {
331 crate::checks::normalize::normalize_dataframe_columns(raw_df, strategy)?;
332 }
333 crate::checks::normalize::normalize_dataframe_columns(&mut typed_df, strategy)?;
334 }
335 Ok(ReadInput::Data {
336 input_file: input_file.clone(),
337 raw_df,
338 typed_df,
339 })
340}
341
342pub(crate) fn build_typed_schema(
343 input_columns: &[String],
344 declared_columns: &[config::ColumnConfig],
345 normalize_strategy: Option<&str>,
346) -> FloeResult<Schema> {
347 let mut declared_types = HashMap::new();
348 for column in declared_columns {
349 declared_types.insert(
350 column.name.as_str(),
351 config::parse_data_type(&column.column_type)?,
352 );
353 }
354
355 let mut schema = Schema::with_capacity(input_columns.len());
356 for name in input_columns {
357 let normalized = if let Some(strategy) = normalize_strategy {
358 crate::checks::normalize::normalize_name(name, strategy)
359 } else {
360 name.to_string()
361 };
362 let dtype = declared_types
363 .get(normalized.as_str())
364 .cloned()
365 .unwrap_or(DataType::String);
366 schema.insert(name.as_str().into(), dtype);
367 }
368 Ok(schema)
369}
370
371pub(crate) fn cast_df_to_string(df: &DataFrame) -> FloeResult<DataFrame> {
372 cast_df_with_type(df, &DataType::String)
373}
374
375pub(crate) fn cast_df_to_schema(df: &DataFrame, schema: &Schema) -> FloeResult<DataFrame> {
376 let mut columns = Vec::with_capacity(schema.len());
377 for (name, dtype) in schema.iter() {
378 let series = df.column(name.as_str()).map_err(|err| {
379 Box::new(ConfigError(format!(
380 "input column {} not found: {err}",
381 name.as_str()
382 )))
383 })?;
384 let casted =
385 if matches!(dtype, DataType::Boolean) && matches!(series.dtype(), DataType::String) {
386 cast_string_to_bool(name.as_str(), series)?
387 } else {
388 series
389 .cast_with_options(dtype, CastOptions::NonStrict)
390 .map_err(|err| {
391 Box::new(ConfigError(format!(
392 "failed to cast input column {}: {err}",
393 name.as_str()
394 )))
395 })?
396 };
397 columns.push(casted);
398 }
399 DataFrame::new(columns).map_err(|err| {
400 Box::new(ConfigError(format!(
401 "failed to build typed dataframe: {err}"
402 ))) as Box<dyn std::error::Error + Send + Sync>
403 })
404}
405
406fn cast_string_to_bool(name: &str, series: &Column) -> FloeResult<Column> {
407 let string_values = series.as_materialized_series().str().map_err(|err| {
408 Box::new(ConfigError(format!(
409 "failed to read boolean column {} as string: {err}",
410 name
411 )))
412 })?;
413 let mut values = Vec::with_capacity(series.len());
414 for value in string_values {
415 let parsed = value.and_then(|raw| match raw.trim().to_ascii_lowercase().as_str() {
416 "true" | "1" => Some(true),
417 "false" | "0" => Some(false),
418 _ => None,
419 });
420 values.push(parsed);
421 }
422 Ok(Series::new(name.into(), values).into())
423}
424
425fn cast_df_with_type(df: &DataFrame, dtype: &DataType) -> FloeResult<DataFrame> {
426 let mut out = df.clone();
427 let names = out
428 .get_column_names()
429 .iter()
430 .map(|name| name.to_string())
431 .collect::<Vec<_>>();
432 for name in names {
433 let series = out.column(&name).map_err(|err| {
434 Box::new(ConfigError(format!(
435 "input column {} not found: {err}",
436 name
437 )))
438 })?;
439 let casted = series
440 .cast_with_options(dtype, CastOptions::NonStrict)
441 .map_err(|err| {
442 Box::new(ConfigError(format!(
443 "failed to cast input column {}: {err}",
444 name
445 )))
446 })?;
447 let idx = out.get_column_index(&name).ok_or_else(|| {
448 Box::new(ConfigError(format!(
449 "input column {} not found for update",
450 name
451 )))
452 })?;
453 out.replace_column(idx, casted).map_err(|err| {
454 Box::new(ConfigError(format!(
455 "failed to update input column {}: {err}",
456 name
457 )))
458 })?;
459 }
460 Ok(out)
461}
462pub fn collect_row_errors(
463 raw_df: &DataFrame,
464 typed_df: &DataFrame,
465 required_cols: &[String],
466 columns: &[config::ColumnConfig],
467 track_cast_errors: bool,
468 raw_indices: &check::ColumnIndex,
469 typed_indices: &check::ColumnIndex,
470) -> FloeResult<Vec<Vec<check::RowError>>> {
471 let mut error_lists = check::not_null_errors(typed_df, required_cols, typed_indices)?;
472 if track_cast_errors {
473 let cast_errors =
474 check::cast_mismatch_errors(raw_df, typed_df, columns, raw_indices, typed_indices)?;
475 for (errors, cast) in error_lists.iter_mut().zip(cast_errors) {
476 errors.extend(cast);
477 }
478 }
479 Ok(error_lists)
480}