Skip to main content

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