buoyant_kernel/lib.rs
1//! # Delta Kernel
2//!
3//! Delta-kernel-rs is an experimental [Delta](https://github.com/delta-io/delta/) implementation
4//! focused on interoperability with a wide range of query engines. It supports reads and
5//! (experimental) writes (only blind appends in the write path currently). This library defines a
6//! number of traits which must be implemented to provide a working delta implementation. They are
7//! detailed below. There is a provided "default engine" that implements all these traits and can
8//! be used to ease integration work. See [`DefaultEngine`](engine/default/index.html) for more
9//! information.
10//!
11//! A full `rust` example for reading table data using the default engine can be found in the
12//! [read-table-single-threaded] example (and for a more complex multi-threaded reader see the
13//! [read-table-multi-threaded] example). An example for reading the table changes for a table
14//! using the default engine can be found in the [read-table-changes] example. The [write-table]
15//! example demonstrates how to write data to a Delta table using the default engine.
16//!
17//! [read-table-single-threaded]:
18//! https://github.com/delta-io/delta-kernel-rs/tree/main/kernel/examples/read-table-single-threaded
19//! [read-table-multi-threaded]:
20//! https://github.com/delta-io/delta-kernel-rs/tree/main/kernel/examples/read-table-multi-threaded
21//! [read-table-changes]:
22//! https://github.com/delta-io/delta-kernel-rs/tree/main/kernel/examples/read-table-changes
23//! [write-table]:
24//! https://github.com/delta-io/delta-kernel-rs/tree/main/kernel/examples/write-table
25//!
26//! # Engine trait
27//!
28//! The [`Engine`] trait allows connectors to bring their own implementation of functionality such
29//! as reading parquet files, listing files in a file system, parsing a JSON string etc. This
30//! trait exposes methods to get sub-engines which expose the core functionalities customizable by
31//! connectors.
32//!
33//! ## Expression handling
34//!
35//! Expression handling is done via the [`EvaluationHandler`], which in turn allows the creation of
36//! [`ExpressionEvaluator`]s. These evaluators are created for a specific predicate [`Expression`]
37//! and allow evaluation of that predicate for a specific batch of data.
38//!
39//! ## File system interactions
40//!
41//! Delta Kernel needs to perform some basic operations against file systems like listing and
42//! reading files. These interactions are encapsulated in the [`StorageHandler`] trait.
43//! Implementers must take care that all assumptions on the behavior of the functions - like sorted
44//! results - are respected.
45//!
46//! ## Reading log and data files
47//!
48//! Delta Kernel requires the capability to read and write json files and read parquet files, which
49//! is exposed via the [`JsonHandler`] and [`ParquetHandler`] respectively. When reading files,
50//! connectors are asked to provide the context information they require to execute the actual
51//! operation. This is done by invoking methods on the [`StorageHandler`] trait.
52
53#![cfg_attr(all(doc, NIGHTLY_CHANNEL), feature(doc_cfg))]
54#![warn(
55 unreachable_pub,
56 trivial_numeric_casts,
57 unused_extern_crates,
58 rust_2018_idioms,
59 rust_2021_compatibility,
60 clippy::unwrap_used,
61 clippy::expect_used,
62 clippy::panic
63)]
64// we re-allow panics in tests
65#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
66
67/// This `extern crate` declaration allows the macro to reliably refer to
68/// `delta_kernel::schema::DataType` no matter which crate invokes it. Without that, `delta_kernel`
69/// cannot invoke the macro because `delta_kernel` is an unknown crate identifier (you have to use
70/// `crate` instead). We could make the macro use `crate::schema::DataType` instead, but then the
71/// macro is useless outside the `delta_kernel` crate.
72// TODO: when running `cargo package -p delta_kernel` this gives 'unused' warning - #1095
73#[allow(unused_extern_crates)]
74extern crate self as delta_kernel;
75
76use std::any::Any;
77use std::fs::DirEntry;
78use std::sync::Arc;
79use std::time::SystemTime;
80use std::{cmp::Ordering, ops::Range};
81
82use bytes::Bytes;
83use url::Url;
84
85use self::schema::{DataType, SchemaRef};
86
87mod action_reconciliation;
88pub mod actions;
89pub mod checkpoint;
90pub mod committer;
91// Public under test-utils so integration tests can inspect CRC state via Snapshot::get_current_crc_if_loaded_for_testing.
92#[cfg(feature = "test-utils")]
93pub mod crc;
94#[cfg(not(feature = "test-utils"))]
95pub(crate) mod crc;
96pub mod engine_data;
97pub mod error;
98pub mod expressions;
99mod log_compaction;
100mod log_path;
101mod log_reader;
102pub mod metrics;
103pub mod scan;
104pub mod schema;
105pub mod snapshot;
106pub mod table_changes;
107pub mod table_configuration;
108pub mod table_features;
109pub mod table_properties;
110pub mod transaction;
111pub mod transforms;
112
113pub use log_path::LogPath;
114
115mod row_tracking;
116
117pub(crate) mod clustering;
118
119mod arrow_compat;
120#[cfg(any(feature = "arrow-57", feature = "arrow-58"))]
121pub use arrow_compat::*;
122
123pub(crate) mod column_trie;
124pub mod kernel_predicates;
125pub(crate) mod utils;
126
127#[cfg(feature = "internal-api")]
128pub use utils::try_parse_uri;
129
130// for the below modules, we cannot introduce a macro to clean this up. rustfmt doesn't follow into
131// macros, and so will not format the files associated with these modules if we get too clever. see:
132// https://github.com/rust-lang/rustfmt/issues/3253
133
134#[cfg(feature = "internal-api")]
135pub mod path;
136#[cfg(not(feature = "internal-api"))]
137pub(crate) mod path;
138
139#[cfg(feature = "internal-api")]
140pub mod log_replay;
141#[cfg(not(feature = "internal-api"))]
142pub(crate) mod log_replay;
143
144#[cfg(feature = "internal-api")]
145pub mod log_segment;
146#[cfg(not(feature = "internal-api"))]
147pub(crate) mod log_segment;
148
149#[cfg(feature = "internal-api")]
150pub mod last_checkpoint_hint;
151#[cfg(not(feature = "internal-api"))]
152pub(crate) mod last_checkpoint_hint;
153
154pub(crate) mod log_segment_files;
155
156#[cfg(feature = "internal-api")]
157pub mod history_manager;
158#[cfg(not(feature = "internal-api"))]
159pub(crate) mod history_manager;
160
161#[cfg(feature = "internal-api")]
162pub mod parallel;
163#[cfg(not(feature = "internal-api"))]
164pub(crate) mod parallel;
165
166pub use action_reconciliation::{ActionReconciliationIterator, ActionReconciliationIteratorState};
167pub use delta_kernel_derive;
168use delta_kernel_derive::internal_api;
169pub use engine_data::{
170 EngineData, FilteredEngineData, FilteredRowVisitor, GetData, RowIndexIterator, RowVisitor,
171};
172pub use error::{DeltaResult, Error};
173pub use expressions::{Expression, ExpressionRef, Predicate, PredicateRef};
174pub use log_compaction::{should_compact, LogCompactionWriter};
175pub use metrics::MetricsReporter;
176pub use snapshot::Snapshot;
177pub use snapshot::SnapshotRef;
178
179use expressions::literal_expression_transform;
180use expressions::Scalar;
181use schema::{StructField, StructType};
182
183#[cfg(any(
184 feature = "default-engine-native-tls",
185 feature = "default-engine-rustls",
186 feature = "arrow-conversion"
187))]
188pub mod engine;
189
190/// Delta table version is 8 byte unsigned int
191pub type Version = u64;
192
193/// Sentinel version indicating a pre-commit state (table does not exist yet).
194/// Used for create-table transactions before the first commit.
195pub const PRE_COMMIT_VERSION: Version = u64::MAX;
196
197pub type FileSize = u64;
198pub type FileIndex = u64;
199
200/// A specification for a range of bytes to read from a file location
201pub type FileSlice = (Url, Option<Range<FileIndex>>);
202
203/// Data read from a Delta table file and the corresponding scan file information.
204pub type FileDataReadResult = (FileMeta, Box<dyn EngineData>);
205
206/// An iterator of data read from specified files
207pub type FileDataReadResultIterator =
208 Box<dyn Iterator<Item = DeltaResult<Box<dyn EngineData>>> + Send>;
209
210/// The metadata that describes an object.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct FileMeta {
213 /// The fully qualified path to the object
214 pub location: Url,
215 /// The last modified time as milliseconds since unix epoch
216 pub last_modified: i64,
217 /// The size in bytes of the object
218 pub size: FileSize,
219}
220
221impl Ord for FileMeta {
222 fn cmp(&self, other: &Self) -> Ordering {
223 self.location.cmp(&other.location)
224 }
225}
226
227impl PartialOrd for FileMeta {
228 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
229 Some(self.cmp(other))
230 }
231}
232
233impl TryFrom<DirEntry> for FileMeta {
234 type Error = Error;
235
236 fn try_from(ent: DirEntry) -> DeltaResult<FileMeta> {
237 let metadata = ent.metadata()?;
238 let last_modified = metadata
239 .modified()?
240 .duration_since(SystemTime::UNIX_EPOCH)
241 .map_err(|_| Error::generic("Failed to convert file timestamp to milliseconds"))?;
242 let location = Url::from_file_path(ent.path())
243 .map_err(|_| Error::generic(format!("Invalid path: {:?}", ent.path())))?;
244 let last_modified = last_modified.as_millis().try_into().map_err(|_| {
245 Error::generic(format!(
246 "Failed to convert file modification time {:?} into i64",
247 last_modified.as_millis()
248 ))
249 })?;
250 Ok(FileMeta {
251 location,
252 last_modified,
253 size: metadata.len(),
254 })
255 }
256}
257
258impl FileMeta {
259 /// Create a new instance of `FileMeta`
260 pub fn new(location: Url, last_modified: i64, size: u64) -> Self {
261 Self {
262 location,
263 last_modified,
264 size,
265 }
266 }
267}
268
269/// Extension trait that makes it easier to work with traits objects that implement [`Any`],
270/// implemented automatically for any type that satisfies `Any`, `Send`, and `Sync`. In particular,
271/// given some `trait T: Any + Send + Sync`, it allows upcasting `T` to `dyn Any + Send + Sync`,
272/// which in turn allows downcasting the result to a concrete type.
273///
274/// For example, the following code will compile:
275///
276/// ```
277/// # use buoyant_kernel as delta_kernel;
278/// # use delta_kernel::AsAny;
279/// # use std::any::Any;
280/// # use std::sync::Arc;
281/// trait Foo : AsAny {}
282/// struct Bar;
283/// impl Foo for Bar {}
284///
285/// let f: Arc<dyn Foo> = Arc::new(Bar);
286/// let a: Arc<dyn Any + Send + Sync> = f.as_any();
287/// let b: Arc<Bar> = a.downcast().unwrap();
288/// ```
289///
290/// In contrast, very similar code that relies only on `Any` would fail to compile:
291///
292/// ```fail_compile
293/// # use std::any::Any;
294/// # use std::sync::Arc;
295/// trait Foo: Any + Send + Sync {}
296///
297/// struct Bar;
298/// impl Foo for Bar {}
299///
300/// let f: Arc<dyn Foo> = Arc::new(Bar);
301/// let b: Arc<Bar> = f.downcast().unwrap(); // `Arc::downcast` method not found
302/// ```
303///
304/// As would this:
305///
306/// ```fail_compile
307/// # use std::any::Any;
308/// # use std::sync::Arc;
309/// trait Foo: Any + Send + Sync {}
310///
311/// struct Bar;
312/// impl Foo for Bar {}
313///
314/// let f: Arc<dyn Foo> = Arc::new(Bar);
315/// let a: Arc<dyn Any + Send + Sync> = f; // trait upcasting coercion is not stable rust
316/// let f: Arc<Bar> = a.downcast().unwrap();
317/// ```
318///
319/// NOTE: `AsAny` inherits the `Send + Sync` constraint from [`Arc::downcast`].
320pub trait AsAny: Any + Send + Sync {
321 /// Obtains a `dyn Any` reference to the object:
322 ///
323 /// ```
324 /// # use buoyant_kernel as delta_kernel;
325 /// # use delta_kernel::AsAny;
326 /// # use std::any::Any;
327 /// # use std::sync::Arc;
328 /// trait Foo : AsAny {}
329 /// struct Bar;
330 /// impl Foo for Bar {}
331 ///
332 /// let f: &dyn Foo = &Bar;
333 /// let a: &dyn Any = f.any_ref();
334 /// let b: &Bar = a.downcast_ref().unwrap();
335 /// ```
336 fn any_ref(&self) -> &(dyn Any + Send + Sync);
337
338 /// Obtains an `Arc<dyn Any>` reference to the object:
339 ///
340 /// ```
341 /// # use buoyant_kernel as delta_kernel;
342 /// # use delta_kernel::AsAny;
343 /// # use std::any::Any;
344 /// # use std::sync::Arc;
345 /// trait Foo : AsAny {}
346 /// struct Bar;
347 /// impl Foo for Bar {}
348 ///
349 /// let f: Arc<dyn Foo> = Arc::new(Bar);
350 /// let a: Arc<dyn Any + Send + Sync> = f.as_any();
351 /// let b: Arc<Bar> = a.downcast().unwrap();
352 /// ```
353 fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
354
355 /// Converts the object to `Box<dyn Any>`:
356 ///
357 /// ```
358 /// # use buoyant_kernel as delta_kernel;
359 /// # use delta_kernel::AsAny;
360 /// # use std::any::Any;
361 /// # use std::sync::Arc;
362 /// trait Foo : AsAny {}
363 /// struct Bar;
364 /// impl Foo for Bar {}
365 ///
366 /// let f: Box<dyn Foo> = Box::new(Bar);
367 /// let a: Box<dyn Any> = f.into_any();
368 /// let b: Box<Bar> = a.downcast().unwrap();
369 /// ```
370 fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
371
372 /// Convenient wrapper for [`std::any::type_name`], since [`Any`] does not provide it and
373 /// [`Any::type_id`] is useless as a debugging aid (its `Debug` is just a mess of hex digits).
374 fn type_name(&self) -> &'static str;
375}
376
377// Blanket implementation for all eligible types
378impl<T: Any + Send + Sync> AsAny for T {
379 fn any_ref(&self) -> &(dyn Any + Send + Sync) {
380 self
381 }
382 fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
383 self
384 }
385 fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync> {
386 self
387 }
388 fn type_name(&self) -> &'static str {
389 std::any::type_name::<Self>()
390 }
391}
392
393/// Extension trait that facilitates object-safe implementations of `PartialEq`.
394pub trait DynPartialEq: AsAny {
395 fn dyn_eq(&self, other: &dyn Any) -> bool;
396}
397
398// Blanket implementation for all eligible types
399impl<T: PartialEq + AsAny> DynPartialEq for T {
400 fn dyn_eq(&self, other: &dyn Any) -> bool {
401 other.downcast_ref::<T>().is_some_and(|other| self == other)
402 }
403}
404
405/// Trait for implementing an Expression evaluator.
406///
407/// It contains one Expression which can be evaluated on multiple ColumnarBatches.
408/// Connectors can implement this trait to optimize the evaluation using the
409/// connector specific capabilities.
410pub trait ExpressionEvaluator: AsAny {
411 /// Evaluate the expression on a given EngineData.
412 ///
413 /// Produces one value for each row of the input.
414 /// The data type of the output is same as the type output of the expression this evaluator is using.
415 fn evaluate(&self, batch: &dyn EngineData) -> DeltaResult<Box<dyn EngineData>>;
416}
417
418/// Trait for implementing a Predicate evaluator.
419///
420/// It contains one Predicate which can be evaluated on multiple ColumnarBatches.
421/// Connectors can implement this trait to optimize the evaluation using the
422/// connector specific capabilities.
423pub trait PredicateEvaluator: AsAny {
424 /// Evaluate the predicate on a given EngineData.
425 ///
426 /// Produces one boolean value for each row of the input.
427 fn evaluate(&self, batch: &dyn EngineData) -> DeltaResult<Box<dyn EngineData>>;
428}
429
430/// Provides expression evaluation capability to Delta Kernel.
431///
432/// Delta Kernel can use this handler to evaluate a predicate on partition filters,
433/// fill up partition column values, and any computation on data using Expressions.
434pub trait EvaluationHandler: AsAny {
435 /// Create an [`ExpressionEvaluator`] that can evaluate the given [`Expression`]
436 /// on columnar batches with the given [`Schema`] to produce data of [`DataType`].
437 ///
438 /// If the provided output type is a struct, its fields describe the columns of output produced
439 /// by the evaluator. Otherwise, the output schema is a single column named "output" of the
440 /// specified `output_type`. In all cases, the output schema is only used for its names (all
441 /// field names will be updated to match) and nullability (non-nullable columns can be converted
442 /// to nullable). Any mismatch in types (including number of columns) will produce an error.
443 ///
444 /// # Parameters
445 ///
446 /// - `input_schema`: Schema of the input data.
447 /// - `expression`: Expression to evaluate.
448 /// - `output_type`: Expected result data type.
449 ///
450 /// [`Schema`]: crate::schema::StructType
451 /// [`DataType`]: crate::schema::DataType
452 fn new_expression_evaluator(
453 &self,
454 input_schema: SchemaRef,
455 expression: ExpressionRef,
456 output_type: DataType,
457 ) -> DeltaResult<Arc<dyn ExpressionEvaluator>>;
458
459 /// Create a [`PredicateEvaluator`] that can evaluate the given [`Predicate`] on columnar
460 /// batches with the given [`Schema`] to produce a column of boolean results.
461 ///
462 /// The output schema is a single nullable boolean column named "output".
463 ///
464 /// # Parameters
465 ///
466 /// - `input_schema`: Schema of the input data.
467 /// - `predicate`: Predicate to evaluate.
468 ///
469 /// [`Schema`]: crate::schema::StructType
470 fn new_predicate_evaluator(
471 &self,
472 input_schema: SchemaRef,
473 predicate: PredicateRef,
474 ) -> DeltaResult<Arc<dyn PredicateEvaluator>>;
475
476 /// Create a single-row all-null-value [`EngineData`] with the schema specified by
477 /// `output_schema`.
478 // NOTE: we should probably allow DataType instead of SchemaRef, but can expand that in the
479 // future.
480 fn null_row(&self, output_schema: SchemaRef) -> DeltaResult<Box<dyn EngineData>>;
481
482 /// Create a multi-row [`EngineData`] by applying the given schema to multiple rows of values.
483 ///
484 /// Each element in `rows` represents one row of data, where each row is a slice of structured
485 /// scalar values (one scalar per top-level field in the schema).
486 ///
487 /// # Parameters
488 ///
489 /// - `schema`: Schema describing the structure of each row.
490 /// - `rows`: Slice of rows, where each row contains one structured scalar per top-level schema
491 /// field.
492 ///
493 /// # Returns
494 ///
495 /// A multi-row `EngineData` containing all rows.
496 ///
497 /// # Errors
498 ///
499 /// Returns an error if any row has a number of scalars that does not match the number of
500 /// top-level fields in `schema`, or if any scalar value cannot be appended to its corresponding
501 /// field's builder (e.g. due to a type mismatch).
502 ///
503 /// # Example
504 ///
505 /// For a schema with fields `[add: Struct, remove: Struct]`, each row should contain exactly 2
506 /// scalars: one for the `add` field and one for the `remove` field.
507 fn create_many(
508 &self,
509 schema: SchemaRef,
510 rows: &[&[Scalar]],
511 ) -> DeltaResult<Box<dyn EngineData>>;
512}
513
514/// Internal trait to allow us to have a private `create_one` API that's implemented for all
515/// EvaluationHandlers.
516// For some reason rustc doesn't detect it's usage so we allow(dead_code) here...
517#[allow(dead_code)]
518#[internal_api]
519trait EvaluationHandlerExtension: EvaluationHandler {
520 /// Create a single-row [`EngineData`] by applying the given schema to the leaf-values given in
521 /// `values`.
522 // Note: we will stick with a Schema instead of DataType (more constrained can expand in
523 // future)
524 fn create_one(&self, schema: SchemaRef, values: &[Scalar]) -> DeltaResult<Box<dyn EngineData>> {
525 // just get a single int column (arbitrary)
526 let null_row_schema = Arc::new(StructType::new_unchecked(vec![StructField::nullable(
527 "null_col",
528 DataType::INTEGER,
529 )]));
530 let null_row = self.null_row(null_row_schema.clone())?;
531
532 // Convert schema and leaf values to an expression
533 let row_expr = literal_expression_transform(schema.as_ref(), values)?;
534
535 let eval =
536 self.new_expression_evaluator(null_row_schema, row_expr.into(), schema.into())?;
537 eval.evaluate(null_row.as_ref())
538 }
539}
540
541// Auto-implement the extension trait for all EvaluationHandlers
542impl<T: EvaluationHandler + ?Sized> EvaluationHandlerExtension for T {}
543
544/// A trait that allows converting a type into (single-row) EngineData
545///
546/// This is typically used with the `#[derive(IntoEngineData)]` macro
547/// which leverages the traits `ToDataType` and `Into<Scalar>` for struct fields
548/// to convert a struct into EngineData.
549///
550/// # Example
551/// ```ignore
552/// # use std::sync::Arc;
553/// # use delta_kernel_derive::{Schema, IntoEngineData};
554///
555/// #[derive(Schema, IntoEngineData)]
556/// struct MyStruct {
557/// a: i32,
558/// b: String,
559/// }
560///
561/// let my_struct = MyStruct { a: 42, b: "Hello".to_string() };
562/// // typically used with ToSchema
563/// let schema = Arc::new(MyStruct::to_schema());
564/// // single-row EngineData
565/// let engine = todo!(); // create an engine
566/// let engine_data = my_struct.into_engine_data(schema, engine);
567/// ```
568#[internal_api]
569pub(crate) trait IntoEngineData {
570 /// Consume this type to produce a single-row EngineData using the provided schema.
571 fn into_engine_data(
572 self,
573 schema: SchemaRef,
574 engine: &dyn Engine,
575 ) -> DeltaResult<Box<dyn EngineData>>;
576}
577
578/// Provides file system related functionalities to Delta Kernel.
579///
580/// Delta Kernel uses this handler whenever it needs to access the underlying
581/// file system where the Delta table is present. Connector implementation of
582/// this trait can hide filesystem specific details from Delta Kernel.
583pub trait StorageHandler: AsAny {
584 /// List the paths in the same directory that are lexicographically greater than
585 /// (UTF-8 sorting) the given `path`. The result should also be sorted by the file name.
586 ///
587 /// If the path is directory-like (ends with '/'), the result should contain
588 /// all the files in the directory.
589 fn list_from(&self, path: &Url)
590 -> DeltaResult<Box<dyn Iterator<Item = DeltaResult<FileMeta>>>>;
591
592 /// Read data specified by the start and end offset from the file.
593 fn read_files(
594 &self,
595 files: Vec<FileSlice>,
596 ) -> DeltaResult<Box<dyn Iterator<Item = DeltaResult<Bytes>>>>;
597
598 /// Copy a file atomically from source to destination. If the destination file already exists,
599 /// it must return Err(Error::FileAlreadyExists).
600 fn copy_atomic(&self, src: &Url, dest: &Url) -> DeltaResult<()>;
601
602 /// Write data to the specified path.
603 ///
604 /// If `overwrite` is false and the file already exists, this must return
605 /// `Err(Error::FileAlreadyExists)`.
606 fn put(&self, path: &Url, data: Bytes, overwrite: bool) -> DeltaResult<()>;
607
608 /// Perform a HEAD request for the given file at a Url, returning the file metadata.
609 ///
610 /// If the file does not exist, this must return an `Err` with [`Error::FileNotFound`].
611 fn head(&self, path: &Url) -> DeltaResult<FileMeta>;
612}
613
614/// Provides JSON handling functionality to Delta Kernel.
615///
616/// Delta Kernel can use this handler to parse JSON strings into Row or read content from JSON files.
617/// Connectors can leverage this trait to provide their best implementation of the JSON parsing
618/// capability to Delta Kernel.
619pub trait JsonHandler: AsAny {
620 /// Parse the given json strings and return the fields requested by output schema as columns in [`EngineData`].
621 /// json_strings MUST be a single column batch of engine data, and the column type must be string
622 fn parse_json(
623 &self,
624 json_strings: Box<dyn EngineData>,
625 output_schema: SchemaRef,
626 ) -> DeltaResult<Box<dyn EngineData>>;
627
628 /// Read and parse the JSON format file at given locations and return the data as EngineData with
629 /// the columns requested by physical schema. Note: The [`FileDataReadResultIterator`] must emit
630 /// data from files in the order that `files` is given. For example if files ["a", "b"] is provided,
631 /// then the engine data iterator must first return all the engine data from file "a", _then_ all
632 /// the engine data from file "b". Moreover, for a given file, all of its [`EngineData`] and
633 /// constituent rows must be in order that they occur in the file. Consider a file with rows
634 /// (1, 2, 3). The following are legal iterator batches:
635 /// iter: [EngineData(1, 2), EngineData(3)]
636 /// iter: [EngineData(1), EngineData(2, 3)]
637 /// iter: [EngineData(1, 2, 3)]
638 /// The following are illegal batches:
639 /// iter: [EngineData(3), EngineData(1, 2)]
640 /// iter: [EngineData(1), EngineData(3, 2)]
641 /// iter: [EngineData(2, 1, 3)]
642 ///
643 /// Additionally, engines may not merge engine data across file boundaries.
644 ///
645 /// # Parameters
646 ///
647 /// - `files` - File metadata for files to be read.
648 /// - `physical_schema` - Select list of columns to read from the JSON file.
649 /// - `predicate` - Optional push-down predicate hint (engine is free to ignore it).
650 fn read_json_files(
651 &self,
652 files: &[FileMeta],
653 physical_schema: SchemaRef,
654 predicate: Option<PredicateRef>,
655 ) -> DeltaResult<FileDataReadResultIterator>;
656
657 /// Atomically (!) write a single JSON file. Each row of the input data should be written as a
658 /// new JSON object appended to the file. this write must:
659 /// (1) serialize the data to newline-delimited json (each row is a json object literal)
660 /// (2) write the data to storage atomically (i.e. if the file already exists, fail unless the
661 /// overwrite flag is set)
662 ///
663 /// For example, the JSON data should be written as { "column1": "val1", "column2": "val2", .. }
664 /// with each row on a new line.
665 ///
666 /// NOTE: Null columns should not be written to the JSON file. For example, if a row has columns
667 /// ["a", "b"] and the value of "b" is null, the JSON object should be written as
668 /// { "a": "..." }. Note that including nulls is technically valid JSON, but would bloat the
669 /// log, therefore we recommend omitting them.
670 ///
671 /// # Parameters
672 ///
673 /// - `path` - URL specifying the location to write the JSON file
674 /// - `data` - Iterator of EngineData to write to the JSON file. Each row should be written as
675 /// a new JSON object appended to the file. (that is, the file is newline-delimited JSON, and
676 /// each row is a JSON object on a single line)
677 /// - `overwrite` - If true, overwrite the file if it exists. If false, the call must fail if
678 /// the file exists.
679 fn write_json_file(
680 &self,
681 path: &Url,
682 data: Box<dyn Iterator<Item = DeltaResult<FilteredEngineData>> + Send + '_>,
683 overwrite: bool,
684 ) -> DeltaResult<()>;
685}
686
687/// Reserved field IDs for metadata columns in Delta tables.
688///
689/// These field IDs are reserved and should not be used for regular table columns.
690/// They are used to provide file-level metadata as virtual columns during reads.
691pub mod reserved_field_ids {
692 /// Reserved field ID for the file name metadata column (`_file`).
693 /// This column provides the name of the Parquet file that contains each row.
694 pub const FILE_NAME: i64 = 2147483646;
695}
696
697/// Metadata from a Parquet file footer.
698///
699/// This struct contains metadata extracted from a Parquet file's footer, including the schema.
700/// It is designed to be extensible for future additions such as row group statistics.
701#[derive(Debug, Clone)]
702pub struct ParquetFooter {
703 /// The schema of the Parquet file, converted to Delta Kernel's schema format.
704 pub schema: SchemaRef,
705}
706
707/// Provides Parquet file related functionalities to Delta Kernel.
708///
709/// Connectors can leverage this trait to provide their own custom
710/// implementation of Parquet data file functionalities to Delta Kernel.
711pub trait ParquetHandler: AsAny {
712 /// Read and parse the Parquet file at given locations and return the data as EngineData with
713 /// the columns requested by physical schema. The ParquetHandler _must_ return exactly the
714 /// columns specified in `physical_schema`, and they _must_ be in schema order.
715 ///
716 /// # Resolving Parquet schema to the physical schema
717 ///
718 /// When reading the Parquet file, the columns are resolved from the Parquet schema to the
719 /// kernel's `physical_schema`. To do so, the parquet reader must match each Parquet column
720 /// to a [`StructField`] in the `physical_schema`. All columns in the returned `EngineData`
721 /// must be in the same order as specified in `physical_schema`.
722 ///
723 /// Parquet columns are matched to `physical_schema` [`StructField`]s using the following rules:
724 /// 1. **Field ID**: If a [`StructField`] in `physical_schema` contains a field ID
725 /// (specified in [`ColumnMetadataKey::ParquetFieldId`] metadata), use the ID to
726 /// match the Parquet column's field id
727 /// 2. **Field Name**: If no field ID is present in the `physical_schema`'s [`StructField`] or no matching parquet field ID is found,
728 /// fall back to matching by column name
729 ///
730 /// # Metadata Columns
731 ///
732 /// The ParquetHandler must support virtual metadata columns that provide additional information
733 /// about each row. These columns are not stored in the Parquet file but are generated at read time.
734 ///
735 /// ## Row Index Column
736 ///
737 /// When a column in `physical_schema` is marked as a row index metadata column (via
738 /// [`StructField::create_metadata_column`] with [`schema::MetadataColumnSpec::RowIndex`]), the
739 /// ParquetHandler must populate it with the 0-based row position within the Parquet file:
740 ///
741 /// - **Column name**: User-specified (commonly `"row_index"` or `"_metadata.row_index"`)
742 /// - **Type**: `LONG` (non-nullable)
743 /// - **Values**: Sequential integers starting at 0 for each file
744 /// - **Use case**: Track row positions for downstream processing, or internally used to compute Row IDs
745 ///
746 /// Example: A file with 5 rows would have row_index values `[0, 1, 2, 3, 4]`.
747 ///
748 /// ## File Name Column (Reserved Field ID)
749 ///
750 /// When a column in `physical_schema` has the reserved field ID
751 /// [`reserved_field_ids::FILE_NAME`] (2147483646), the ParquetHandler must populate it
752 /// with the file path/name:
753 ///
754 /// - **Column name**: `"_file"`
755 /// - **Type**: `STRING` (non-nullable)
756 /// - **Field ID**: 2147483646 (reserved)
757 /// - **Values**: The file path/URL (e.g., `"s3://bucket/path/file.parquet"`)
758 /// - **Use case**: Track which file each row came from in multi-file reads
759 ///
760 /// Example: All rows from the same file would have the same `_file` value.
761 ///
762 /// ## Metadata Column Examples
763 ///
764 /// ```rust,ignore
765 /// use delta_kernel::schema::{StructType, StructField, DataType, MetadataColumnSpec};
766 ///
767 /// // Example 1: Schema with row_index metadata column
768 /// let schema_with_row_index = StructType::try_new([
769 /// StructField::nullable("id", DataType::INTEGER),
770 /// StructField::create_metadata_column("row_index", MetadataColumnSpec::RowIndex),
771 /// StructField::nullable("value", DataType::STRING),
772 /// ])?;
773 ///
774 /// // Example 2: Schema with _file metadata column (using reserved field ID)
775 /// let schema_with_file_path = StructType::try_new([
776 /// StructField::nullable("id", DataType::INTEGER),
777 /// StructField::create_metadata_column("_file", MetadataColumnSpec::FilePath),
778 /// StructField::nullable("value", DataType::STRING),
779 /// ])?;
780 /// ```
781 ///
782 /// ---
783 ///
784 /// If no matching Parquet column is found, `NULL` values are returned
785 /// for nullable columns in `physical_schema`. For non-nullable columns, an error is returned.
786 ///
787 ///
788 /// ## Column Matching Examples
789 ///
790 /// Consider a `physical_schema` with the following fields:
791 /// - Column 0: `"i_logical"` (integer, non-null) with field ID 1 (via [`ColumnMetadataKey::ParquetFieldId`])
792 /// - Column 1: `"s"` (string, nullable) with no field ID metadata
793 /// - Column 2: `"i2"` (integer, nullable) with no field ID metadata
794 ///
795 /// [`ColumnMetadataKey::ParquetFieldId`]: crate::schema::ColumnMetadataKey::ParquetFieldId
796 ///
797 /// And a Parquet file containing these columns:
798 /// - Column 0: `"i2"` (integer, nullable) with field ID 3
799 /// - Column 1: `"i"` (integer, non-null) with field ID 1
800 /// - No `"s"` column present
801 ///
802 /// The column matching would work as follows:
803 /// - `"i_logical"` matches `"i"` by field ID (both have ID 1)
804 /// - `"i2"` matches `"i2"` by column name (no field ID to match on)
805 /// - `"s"` has no matching Parquet column, so NULL values are returned
806 ///
807 /// The returned data will contain exactly 3 columns in physical schema order:
808 /// `{i_logical: parquet[1], s: NULL.., i2: parquet[0]}`
809 ///
810 /// # Parameters
811 ///
812 /// - `files` - File metadata for files to be read.
813 /// - `physical_schema` - Select list and order of columns to read from the Parquet file.
814 /// - `predicate` - Optional push-down predicate hint (engine is free to ignore it).
815 ///
816 /// # Returns
817 /// A [`DeltaResult`] containing a [`FileDataReadResultIterator`].
818 /// Each element of the iterator is a [`DeltaResult`] of [`EngineData`]. The [`EngineData`]
819 /// has the contents of `files` and must match the provided `physical_schema`.
820 ///
821 /// Note: The [`FileDataReadResultIterator`] must emit data from files in the order that `files`
822 /// is given. For example if files ["a", "b"] is provided, then the engine data iterator must
823 /// first return all the engine data from file "a", _then_ all the engine data from file "b".
824 /// Moreover, for a given file, all of its [`EngineData`] and constituent rows must be in order
825 /// that they occur in the file. Consider a file with rows
826 /// (1, 2, 3). The following are legal iterator batches:
827 /// iter: [EngineData(1, 2), EngineData(3)]
828 /// iter: [EngineData(1), EngineData(2, 3)]
829 /// iter: [EngineData(1, 2, 3)]
830 /// The following are illegal batches:
831 /// iter: [EngineData(3), EngineData(1, 2)]
832 /// iter: [EngineData(1), EngineData(3, 2)]
833 /// iter: [EngineData(2, 1, 3)]
834 ///
835 /// Additionally, engines must not merge engine data across file boundaries.
836 ///
837 /// [`ColumnMetadataKey::ParquetFieldId`]: crate::schema::ColumnMetadataKey
838 fn read_parquet_files(
839 &self,
840 files: &[FileMeta],
841 physical_schema: SchemaRef,
842 predicate: Option<PredicateRef>,
843 ) -> DeltaResult<FileDataReadResultIterator>;
844
845 /// Write data to a Parquet file at the specified URL.
846 ///
847 /// This method writes the provided `data` to a Parquet file at the given `url`.
848 ///
849 /// This will overwrite the file if it already exists.
850 ///
851 /// # Parameters
852 ///
853 /// - `url` - The full URL path where the Parquet file should be written
854 /// (e.g., `s3://bucket/path/file.parquet`).
855 /// - `data` - An iterator of engine data to be written to the Parquet file.
856 ///
857 /// # Returns
858 ///
859 /// A [`DeltaResult`] indicating success or failure.
860 fn write_parquet_file(
861 &self,
862 location: url::Url,
863 data: Box<dyn Iterator<Item = DeltaResult<Box<dyn EngineData>>> + Send>,
864 ) -> DeltaResult<()>;
865
866 /// Read the footer metadata from a Parquet file without reading the data.
867 ///
868 /// This method reads only the Parquet file footer (metadata section), which is useful for
869 /// schema inspection, compatibility checking, and determining whether parsed statistics
870 /// columns are present and compatible with the current table schema.
871 ///
872 /// # Parameters
873 ///
874 /// - `file` - File metadata for the Parquet file whose footer should be read. The `size` field
875 /// should contain the actual file size to enable efficient footer reads without additional
876 /// I/O operations.
877 ///
878 /// # Returns
879 ///
880 /// A [`DeltaResult`] containing a [`ParquetFooter`] with the Parquet file's metadata, including
881 /// the schema converted to Delta Kernel's format.
882 ///
883 /// # Field IDs
884 ///
885 /// If the Parquet file contains field IDs (written when column mapping is enabled), they are
886 /// preserved in each [`StructField`]'s metadata. Callers can access field IDs via
887 /// [`StructField::get_config_value`] with [`ColumnMetadataKey::ParquetFieldId`].
888 ///
889 /// # Errors
890 ///
891 /// Returns an error if:
892 /// - The file cannot be accessed or does not exist
893 /// - The file is not a valid Parquet file
894 /// - The footer cannot be read or parsed
895 /// - The schema cannot be converted to Delta Kernel's format
896 ///
897 /// [`StructField`]: crate::schema::StructField
898 /// [`StructField::get_config_value`]: crate::schema::StructField::get_config_value
899 /// [`ColumnMetadataKey::ParquetFieldId`]: crate::schema::ColumnMetadataKey::ParquetFieldId
900 fn read_parquet_footer(&self, file: &FileMeta) -> DeltaResult<ParquetFooter>;
901}
902
903/// The `Engine` trait encapsulates all the functionality an engine or connector needs to provide
904/// to the Delta Kernel in order to read the Delta table.
905///
906/// Engines/Connectors are expected to pass an implementation of this trait when reading a Delta
907/// table.
908pub trait Engine: AsAny {
909 /// Get the connector provided [`EvaluationHandler`].
910 fn evaluation_handler(&self) -> Arc<dyn EvaluationHandler>;
911
912 /// Get the connector provided [`StorageHandler`]
913 fn storage_handler(&self) -> Arc<dyn StorageHandler>;
914
915 /// Get the connector provided [`JsonHandler`].
916 fn json_handler(&self) -> Arc<dyn JsonHandler>;
917
918 /// Get the connector provided [`ParquetHandler`].
919 fn parquet_handler(&self) -> Arc<dyn ParquetHandler>;
920
921 /// Get the connector provided [`MetricsReporter`] for metrics collection.
922 ///
923 /// Returns an optional reporter that will receive metric events from Delta operations.
924 /// The default implementation returns None (no metrics reporting).
925 fn get_metrics_reporter(&self) -> Option<Arc<dyn MetricsReporter>> {
926 None
927 }
928}
929
930// we have an 'internal' feature flag: default-engine-base, which is actually just the shared
931// pieces of default-engine-native-tls and default-engine-rustls. the crate can't compile with _only_
932// default-engine-base, so we give a friendly error here.
933#[cfg(all(
934 feature = "default-engine-base",
935 not(any(
936 feature = "default-engine-native-tls",
937 feature = "default-engine-rustls",
938 ))
939))]
940compile_error!(
941 "The default-engine-base feature flag is not meant to be used directly. \
942 Please use either default-engine-native-tls or default-engine-rustls."
943);
944
945// Rustdoc's documentation tests can do some things that regular unit tests can't. Here we are
946// using doctests to test macros. Specifically, we are testing for failed macro invocations due
947// to invalid input, not the macro output when the macro invocation is successful (which can/should be
948// done in unit tests). This module is not exclusively for macro tests only so other doctests can also be added.
949// https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#include-items-only-when-collecting-doctests
950#[cfg(doctest)]
951mod doctests;