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
167pub mod history_manager;
168
169#[cfg(feature = "internal-api")]
170pub mod parallel;
171#[cfg(not(feature = "internal-api"))]
172pub(crate) mod parallel;
173
174pub use action_reconciliation::{ActionReconciliationIterator, ActionReconciliationIteratorState};
175pub use delta_kernel_derive;
176use delta_kernel_derive::internal_api;
177pub use engine_data::{
178 EngineData, FilteredEngineData, FilteredRowVisitor, GetData, RowIndexIterator, RowVisitor,
179};
180pub use error::{DeltaResult, Error};
181use expressions::{literal_expression_transform, Scalar};
182pub use expressions::{Expression, ExpressionRef, Predicate, PredicateRef};
183pub use log_compaction::{should_compact, LogCompactionWriter};
184use schema::{StructField, StructType};
185pub use snapshot::{Snapshot, SnapshotRef};
186
187#[cfg(any(
188 feature = "default-engine-native-tls",
189 feature = "default-engine-rustls",
190 feature = "arrow-conversion"
191))]
192pub mod engine;
193
194/// Delta table version is 8 byte unsigned int
195pub type Version = u64;
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
415 /// using.
416 fn evaluate(&self, batch: &dyn EngineData) -> DeltaResult<Box<dyn EngineData>>;
417}
418
419/// Trait for implementing a Predicate evaluator.
420///
421/// It contains one Predicate which can be evaluated on multiple ColumnarBatches.
422/// Connectors can implement this trait to optimize the evaluation using the
423/// connector specific capabilities.
424pub trait PredicateEvaluator: AsAny {
425 /// Evaluate the predicate on a given EngineData.
426 ///
427 /// Produces one boolean value for each row of the input.
428 fn evaluate(&self, batch: &dyn EngineData) -> DeltaResult<Box<dyn EngineData>>;
429}
430
431/// Provides expression evaluation capability to Delta Kernel.
432///
433/// Delta Kernel can use this handler to evaluate a predicate on partition filters,
434/// fill up partition column values, and any computation on data using Expressions.
435pub trait EvaluationHandler: AsAny {
436 /// Create an [`ExpressionEvaluator`] that can evaluate the given [`Expression`]
437 /// on columnar batches with the given [`Schema`] to produce data of [`DataType`].
438 ///
439 /// If the provided output type is a struct, its fields describe the columns of output produced
440 /// by the evaluator. Otherwise, the output schema is a single column named "output" of the
441 /// specified `output_type`. In all cases, the output schema is only used for its names (all
442 /// field names will be updated to match) and nullability (non-nullable columns can be converted
443 /// to nullable). Any mismatch in types (including number of columns) will produce an error.
444 ///
445 /// # Parameters
446 ///
447 /// - `input_schema`: Schema of the input data.
448 /// - `expression`: Expression to evaluate.
449 /// - `output_type`: Expected result data type.
450 ///
451 /// [`Schema`]: crate::schema::StructType
452 /// [`DataType`]: crate::schema::DataType
453 fn new_expression_evaluator(
454 &self,
455 input_schema: SchemaRef,
456 expression: ExpressionRef,
457 output_type: DataType,
458 ) -> DeltaResult<Arc<dyn ExpressionEvaluator>>;
459
460 /// Create a [`PredicateEvaluator`] that can evaluate the given [`Predicate`] on columnar
461 /// batches with the given [`Schema`] to produce a column of boolean results.
462 ///
463 /// The output schema is a single nullable boolean column named "output".
464 ///
465 /// # Parameters
466 ///
467 /// - `input_schema`: Schema of the input data.
468 /// - `predicate`: Predicate to evaluate.
469 ///
470 /// [`Schema`]: crate::schema::StructType
471 fn new_predicate_evaluator(
472 &self,
473 input_schema: SchemaRef,
474 predicate: PredicateRef,
475 ) -> DeltaResult<Arc<dyn PredicateEvaluator>>;
476
477 /// Create a single-row all-null-value [`EngineData`] with the schema specified by
478 /// `output_schema`.
479 // NOTE: we should probably allow DataType instead of SchemaRef, but can expand that in the
480 // future.
481 fn null_row(&self, output_schema: SchemaRef) -> DeltaResult<Box<dyn EngineData>>;
482
483 /// Create a multi-row [`EngineData`] by applying the given schema to multiple rows of values.
484 ///
485 /// Each element in `rows` represents one row of data, where each row is a slice of structured
486 /// scalar values (one scalar per top-level field in the schema).
487 ///
488 /// # Parameters
489 ///
490 /// - `schema`: Schema describing the structure of each row.
491 /// - `rows`: Slice of rows, where each row contains one structured scalar per top-level schema
492 /// field.
493 ///
494 /// # Returns
495 ///
496 /// A multi-row `EngineData` containing all rows.
497 ///
498 /// # Errors
499 ///
500 /// Returns an error if any row has a number of scalars that does not match the number of
501 /// top-level fields in `schema`, or if any scalar value cannot be appended to its corresponding
502 /// field's builder (e.g. due to a type mismatch).
503 ///
504 /// # Example
505 ///
506 /// For a schema with fields `[add: Struct, remove: Struct]`, each row should contain exactly 2
507 /// scalars: one for the `add` field and one for the `remove` field.
508 fn create_many(
509 &self,
510 schema: SchemaRef,
511 rows: &[&[Scalar]],
512 ) -> DeltaResult<Box<dyn EngineData>>;
513}
514
515/// Internal trait to allow us to have a private `create_one` API that's implemented for all
516/// EvaluationHandlers.
517// For some reason rustc doesn't detect it's usage so we allow(dead_code) here...
518#[allow(dead_code)]
519#[internal_api]
520trait EvaluationHandlerExtension: EvaluationHandler {
521 /// Create a single-row [`EngineData`] by applying the given schema to the leaf-values given in
522 /// `values`.
523 // Note: we will stick with a Schema instead of DataType (more constrained can expand in
524 // future)
525 fn create_one(&self, schema: SchemaRef, values: &[Scalar]) -> DeltaResult<Box<dyn EngineData>> {
526 // just get a single int column (arbitrary)
527 let null_row_schema = Arc::new(StructType::new_unchecked(vec![StructField::nullable(
528 "null_col",
529 DataType::INTEGER,
530 )]));
531 let null_row = self.null_row(null_row_schema.clone())?;
532
533 // Convert schema and leaf values to an expression
534 let row_expr = literal_expression_transform(schema.as_ref(), values)?;
535
536 let eval =
537 self.new_expression_evaluator(null_row_schema, row_expr.into(), schema.into())?;
538 eval.evaluate(null_row.as_ref())
539 }
540}
541
542// Auto-implement the extension trait for all EvaluationHandlers
543impl<T: EvaluationHandler + ?Sized> EvaluationHandlerExtension for T {}
544
545/// A trait that allows converting a type into (single-row) EngineData
546///
547/// This is typically used with the `#[derive(IntoEngineData)]` macro
548/// which leverages the traits `ToDataType` and `Into<Scalar>` for struct fields
549/// to convert a struct into EngineData.
550///
551/// # Example
552/// ```ignore
553/// # use std::sync::Arc;
554/// # use delta_kernel_derive::{Schema, IntoEngineData};
555///
556/// #[derive(Schema, IntoEngineData)]
557/// struct MyStruct {
558/// a: i32,
559/// b: String,
560/// }
561///
562/// let my_struct = MyStruct { a: 42, b: "Hello".to_string() };
563/// // typically used with ToSchema
564/// let schema = Arc::new(MyStruct::to_schema());
565/// // single-row EngineData
566/// let engine = todo!(); // create an engine
567/// let engine_data = my_struct.into_engine_data(schema, engine);
568/// ```
569#[internal_api]
570pub(crate) trait IntoEngineData {
571 /// Consume this type to produce a single-row EngineData using the provided schema.
572 fn into_engine_data(
573 self,
574 schema: SchemaRef,
575 engine: &dyn Engine,
576 ) -> DeltaResult<Box<dyn EngineData>>;
577}
578
579/// Provides file system related functionalities to Delta Kernel.
580///
581/// Delta Kernel uses this handler whenever it needs to access the underlying
582/// file system where the Delta table is present. Connector implementation of
583/// this trait can hide filesystem specific details from Delta Kernel.
584pub trait StorageHandler: AsAny {
585 /// List the paths in the same directory that are lexicographically greater than
586 /// (UTF-8 sorting) the given `path`. The result should also be sorted by the file name.
587 ///
588 /// If the path is directory-like (ends with '/'), the result should contain
589 /// all the files in the directory.
590 fn list_from(&self, path: &Url)
591 -> DeltaResult<Box<dyn Iterator<Item = DeltaResult<FileMeta>>>>;
592
593 /// Read data specified by the start and end offset from the file.
594 fn read_files(
595 &self,
596 files: Vec<FileSlice>,
597 ) -> DeltaResult<Box<dyn Iterator<Item = DeltaResult<Bytes>>>>;
598
599 /// Copy a file atomically from source to destination. If the destination file already exists,
600 /// it must return Err(Error::FileAlreadyExists).
601 fn copy_atomic(&self, src: &Url, dest: &Url) -> DeltaResult<()>;
602
603 /// Write data to the specified path.
604 ///
605 /// If `overwrite` is false and the file already exists, this must return
606 /// `Err(Error::FileAlreadyExists)`.
607 fn put(&self, path: &Url, data: Bytes, overwrite: bool) -> DeltaResult<()>;
608
609 /// Perform a HEAD request for the given file at a Url, returning the file metadata.
610 ///
611 /// If the file does not exist, this must return an `Err` with [`Error::FileNotFound`].
612 fn head(&self, path: &Url) -> DeltaResult<FileMeta>;
613}
614
615/// Provides JSON handling functionality to Delta Kernel.
616///
617/// Delta Kernel can use this handler to parse JSON strings into Row or read content from JSON
618/// files. Connectors can leverage this trait to provide their best implementation of the JSON
619/// parsing capability to Delta Kernel.
620pub trait JsonHandler: AsAny {
621 /// Parse the given json strings and return the fields requested by output schema as columns in
622 /// [`EngineData`]. json_strings MUST be a single column batch of engine data, and the
623 /// column type must be string
624 fn parse_json(
625 &self,
626 json_strings: Box<dyn EngineData>,
627 output_schema: SchemaRef,
628 ) -> DeltaResult<Box<dyn EngineData>>;
629
630 /// Read and parse the JSON format file at given locations and return the data as EngineData
631 /// with the columns requested by physical schema. Note: The [`FileDataReadResultIterator`]
632 /// must emit data from files in the order that `files` is given. For example if files ["a",
633 /// "b"] is provided, then the engine data iterator must first return all the engine data
634 /// from file "a", _then_ all the engine data from file "b". Moreover, for a given file, all
635 /// of its [`EngineData`] and constituent rows must be in order that they occur in the file.
636 /// Consider a file with rows (1, 2, 3). The following are legal iterator batches:
637 /// iter: [EngineData(1, 2), EngineData(3)]
638 /// iter: [EngineData(1), EngineData(2, 3)]
639 /// iter: [EngineData(1, 2, 3)]
640 /// The following are illegal batches:
641 /// iter: [EngineData(3), EngineData(1, 2)]
642 /// iter: [EngineData(1), EngineData(3, 2)]
643 /// iter: [EngineData(2, 1, 3)]
644 ///
645 /// Additionally, engines may not merge engine data across file boundaries.
646 ///
647 /// # Parameters
648 ///
649 /// - `files` - File metadata for files to be read.
650 /// - `physical_schema` - Select list of columns to read from the JSON file.
651 /// - `predicate` - Optional push-down predicate hint (engine is free to ignore it).
652 fn read_json_files(
653 &self,
654 files: &[FileMeta],
655 physical_schema: SchemaRef,
656 predicate: Option<PredicateRef>,
657 ) -> DeltaResult<FileDataReadResultIterator>;
658
659 /// Atomically (!) write a single JSON file. Each row of the input data should be written as a
660 /// new JSON object appended to the file. this write must:
661 /// (1) serialize the data to newline-delimited json (each row is a json object literal)
662 /// (2) write the data to storage atomically (i.e. if the file already exists, fail unless the
663 /// overwrite flag is set)
664 ///
665 /// For example, the JSON data should be written as { "column1": "val1", "column2": "val2", .. }
666 /// with each row on a new line.
667 ///
668 /// NOTE: Null columns should not be written to the JSON file. For example, if a row has columns
669 /// ["a", "b"] and the value of "b" is null, the JSON object should be written as
670 /// { "a": "..." }. Note that including nulls is technically valid JSON, but would bloat the
671 /// log, therefore we recommend omitting them.
672 ///
673 /// # Parameters
674 ///
675 /// - `path` - URL specifying the location to write the JSON file
676 /// - `data` - Iterator of EngineData to write to the JSON file. Each row should be written as a
677 /// new JSON object appended to the file. (that is, the file is newline-delimited JSON, and
678 /// each row is a JSON object on a single line)
679 /// - `overwrite` - If true, overwrite the file if it exists. If false, the call must fail if
680 /// the file exists.
681 fn write_json_file(
682 &self,
683 path: &Url,
684 data: Box<dyn Iterator<Item = DeltaResult<FilteredEngineData>> + Send + '_>,
685 overwrite: bool,
686 ) -> DeltaResult<()>;
687}
688
689/// Reserved field IDs for metadata columns in Delta tables.
690///
691/// These field IDs are reserved and should not be used for regular table columns.
692/// They are used to provide file-level metadata as virtual columns during reads.
693pub mod reserved_field_ids {
694 /// Reserved field ID for the file name metadata column (`_file`).
695 /// This column provides the name of the Parquet file that contains each row.
696 pub const FILE_NAME: i64 = 2147483646;
697}
698
699/// Metadata from a Parquet file footer.
700///
701/// This struct contains metadata extracted from a Parquet file's footer, including the schema.
702/// It is designed to be extensible for future additions such as row group statistics.
703#[derive(Debug, Clone)]
704pub struct ParquetFooter {
705 /// The schema of the Parquet file, converted to Delta Kernel's schema format.
706 pub schema: SchemaRef,
707}
708
709/// Provides Parquet file related functionalities to Delta Kernel.
710///
711/// Connectors can leverage this trait to provide their own custom
712/// implementation of Parquet data file functionalities to Delta Kernel.
713pub trait ParquetHandler: AsAny {
714 /// Read and parse the Parquet file at given locations and return the data as EngineData with
715 /// the columns requested by physical schema. The ParquetHandler _must_ return exactly the
716 /// columns specified in `physical_schema`, and they _must_ be in schema order.
717 ///
718 /// # Resolving Parquet schema to the physical schema
719 ///
720 /// When reading the Parquet file, the columns are resolved from the Parquet schema to the
721 /// kernel's `physical_schema`. To do so, the parquet reader must match each Parquet column
722 /// to a [`StructField`] in the `physical_schema`. All columns in the returned `EngineData`
723 /// must be in the same order as specified in `physical_schema`.
724 ///
725 /// Parquet columns are matched to `physical_schema` [`StructField`]s using the following rules:
726 /// 1. **Field ID**: If a [`StructField`] in `physical_schema` contains a field ID (specified in
727 /// [`ColumnMetadataKey::ParquetFieldId`] metadata), use the ID to match the Parquet column's
728 /// field id
729 /// 2. **Field Name**: If no field ID is present in the `physical_schema`'s [`StructField`] or
730 /// no matching parquet field ID is found, fall back to matching by column name
731 ///
732 /// # Metadata Columns
733 ///
734 /// The ParquetHandler must support virtual metadata columns that provide additional information
735 /// about each row. These columns are not stored in the Parquet file but are generated at read
736 /// time.
737 ///
738 /// ## Row Index Column
739 ///
740 /// When a column in `physical_schema` is marked as a row index metadata column (via
741 /// [`StructField::create_metadata_column`] with [`schema::MetadataColumnSpec::RowIndex`]), the
742 /// ParquetHandler must populate it with the 0-based row position within the Parquet file:
743 ///
744 /// - **Column name**: User-specified (commonly `"row_index"` or `"_metadata.row_index"`)
745 /// - **Type**: `LONG` (non-nullable)
746 /// - **Values**: Sequential integers starting at 0 for each file
747 /// - **Use case**: Track row positions for downstream processing, or internally used to compute
748 /// Row IDs
749 ///
750 /// Example: A file with 5 rows would have row_index values `[0, 1, 2, 3, 4]`.
751 ///
752 /// ## File Name Column (Reserved Field ID)
753 ///
754 /// When a column in `physical_schema` has the reserved field ID
755 /// [`reserved_field_ids::FILE_NAME`] (2147483646), the ParquetHandler must populate it
756 /// with the file path/name:
757 ///
758 /// - **Column name**: `"_file"`
759 /// - **Type**: `STRING` (non-nullable)
760 /// - **Field ID**: 2147483646 (reserved)
761 /// - **Values**: The file path/URL (e.g., `"s3://bucket/path/file.parquet"`)
762 /// - **Use case**: Track which file each row came from in multi-file reads
763 ///
764 /// Example: All rows from the same file would have the same `_file` value.
765 ///
766 /// ## Metadata Column Examples
767 ///
768 /// ```rust,ignore
769 /// use delta_kernel::schema::{StructType, StructField, DataType, MetadataColumnSpec};
770 ///
771 /// // Example 1: Schema with row_index metadata column
772 /// let schema_with_row_index = StructType::try_new([
773 /// StructField::nullable("id", DataType::INTEGER),
774 /// StructField::create_metadata_column("row_index", MetadataColumnSpec::RowIndex),
775 /// StructField::nullable("value", DataType::STRING),
776 /// ])?;
777 ///
778 /// // Example 2: Schema with _file metadata column (using reserved field ID)
779 /// let schema_with_file_path = StructType::try_new([
780 /// StructField::nullable("id", DataType::INTEGER),
781 /// StructField::create_metadata_column("_file", MetadataColumnSpec::FilePath),
782 /// StructField::nullable("value", DataType::STRING),
783 /// ])?;
784 /// ```
785 ///
786 /// ---
787 ///
788 /// If no matching Parquet column is found, `NULL` values are returned
789 /// for nullable columns in `physical_schema`. For non-nullable columns, an error is returned.
790 ///
791 ///
792 /// ## Column Matching Examples
793 ///
794 /// Consider a `physical_schema` with the following fields:
795 /// - Column 0: `"i_logical"` (integer, non-null) with field ID 1 (via
796 /// [`ColumnMetadataKey::ParquetFieldId`])
797 /// - Column 1: `"s"` (string, nullable) with no field ID metadata
798 /// - Column 2: `"i2"` (integer, nullable) with no field ID metadata
799 ///
800 /// [`ColumnMetadataKey::ParquetFieldId`]: crate::schema::ColumnMetadataKey::ParquetFieldId
801 ///
802 /// And a Parquet file containing these columns:
803 /// - Column 0: `"i2"` (integer, nullable) with field ID 3
804 /// - Column 1: `"i"` (integer, non-null) with field ID 1
805 /// - No `"s"` column present
806 ///
807 /// The column matching would work as follows:
808 /// - `"i_logical"` matches `"i"` by field ID (both have ID 1)
809 /// - `"i2"` matches `"i2"` by column name (no field ID to match on)
810 /// - `"s"` has no matching Parquet column, so NULL values are returned
811 ///
812 /// The returned data will contain exactly 3 columns in physical schema order:
813 /// `{i_logical: parquet[1], s: NULL.., i2: parquet[0]}`
814 ///
815 /// # Parameters
816 ///
817 /// - `files` - File metadata for files to be read.
818 /// - `physical_schema` - Select list and order of columns to read from the Parquet file.
819 /// - `predicate` - Optional push-down predicate hint (engine is free to ignore it).
820 ///
821 /// # Returns
822 /// A [`DeltaResult`] containing a [`FileDataReadResultIterator`].
823 /// Each element of the iterator is a [`DeltaResult`] of [`EngineData`]. The [`EngineData`]
824 /// has the contents of `files` and must match the provided `physical_schema`.
825 ///
826 /// Note: The [`FileDataReadResultIterator`] must emit data from files in the order that `files`
827 /// is given. For example if files ["a", "b"] is provided, then the engine data iterator must
828 /// first return all the engine data from file "a", _then_ all the engine data from file "b".
829 /// Moreover, for a given file, all of its [`EngineData`] and constituent rows must be in order
830 /// that they occur in the file. Consider a file with rows
831 /// (1, 2, 3). The following are legal iterator batches:
832 /// iter: [EngineData(1, 2), EngineData(3)]
833 /// iter: [EngineData(1), EngineData(2, 3)]
834 /// iter: [EngineData(1, 2, 3)]
835 /// The following are illegal batches:
836 /// iter: [EngineData(3), EngineData(1, 2)]
837 /// iter: [EngineData(1), EngineData(3, 2)]
838 /// iter: [EngineData(2, 1, 3)]
839 ///
840 /// Additionally, engines must not merge engine data across file boundaries.
841 ///
842 /// [`ColumnMetadataKey::ParquetFieldId`]: crate::schema::ColumnMetadataKey
843 fn read_parquet_files(
844 &self,
845 files: &[FileMeta],
846 physical_schema: SchemaRef,
847 predicate: Option<PredicateRef>,
848 ) -> DeltaResult<FileDataReadResultIterator>;
849
850 /// Write data to a Parquet file at the specified URL.
851 ///
852 /// This method writes the provided `data` to a Parquet file at the given `url`.
853 ///
854 /// This will overwrite the file if it already exists. For filesystem-backed
855 /// implementations, the parent directories must be created if they do not exist.
856 ///
857 /// # Parameters
858 ///
859 /// - `url` - The full URL path where the Parquet file should be written (e.g.,
860 /// `s3://bucket/path/file.parquet`).
861 /// - `data` - An iterator of engine data to be written to the Parquet file.
862 ///
863 /// # Returns
864 ///
865 /// A [`DeltaResult`] indicating success or failure.
866 fn write_parquet_file(
867 &self,
868 location: url::Url,
869 data: Box<dyn Iterator<Item = DeltaResult<Box<dyn EngineData>>> + Send>,
870 ) -> DeltaResult<()>;
871
872 /// Read the footer metadata from a Parquet file without reading the data.
873 ///
874 /// This method reads only the Parquet file footer (metadata section), which is useful for
875 /// schema inspection, compatibility checking, and determining whether parsed statistics
876 /// columns are present and compatible with the current table schema.
877 ///
878 /// # Parameters
879 ///
880 /// - `file` - File metadata for the Parquet file whose footer should be read. The `size` field
881 /// should contain the actual file size to enable efficient footer reads without additional
882 /// I/O operations.
883 ///
884 /// # Returns
885 ///
886 /// A [`DeltaResult`] containing a [`ParquetFooter`] with the Parquet file's metadata, including
887 /// the schema converted to Delta Kernel's format.
888 ///
889 /// # Field IDs
890 ///
891 /// If the Parquet file contains field IDs (written when column mapping is enabled), they are
892 /// preserved in each [`StructField`]'s metadata. Callers can access field IDs via
893 /// [`StructField::get_config_value`] with [`ColumnMetadataKey::ParquetFieldId`].
894 ///
895 /// # Errors
896 ///
897 /// Returns an error if:
898 /// - The file cannot be accessed or does not exist
899 /// - The file is not a valid Parquet file
900 /// - The footer cannot be read or parsed
901 /// - The schema cannot be converted to Delta Kernel's format
902 ///
903 /// [`StructField`]: crate::schema::StructField
904 /// [`StructField::get_config_value`]: crate::schema::StructField::get_config_value
905 /// [`ColumnMetadataKey::ParquetFieldId`]: crate::schema::ColumnMetadataKey::ParquetFieldId
906 fn read_parquet_footer(&self, file: &FileMeta) -> DeltaResult<ParquetFooter>;
907}
908
909/// The `Engine` trait encapsulates all the functionality an engine or connector needs to provide
910/// to the Delta Kernel in order to read the Delta table.
911///
912/// Engines/Connectors are expected to pass an implementation of this trait when reading a Delta
913/// table.
914pub trait Engine: AsAny {
915 /// Get the connector provided [`EvaluationHandler`].
916 fn evaluation_handler(&self) -> Arc<dyn EvaluationHandler>;
917
918 /// Get the connector provided [`StorageHandler`]
919 fn storage_handler(&self) -> Arc<dyn StorageHandler>;
920
921 /// Get the connector provided [`JsonHandler`].
922 fn json_handler(&self) -> Arc<dyn JsonHandler>;
923
924 /// Get the connector provided [`ParquetHandler`].
925 fn parquet_handler(&self) -> Arc<dyn ParquetHandler>;
926}
927
928// we have an 'internal' feature flag: default-engine-base, which is actually just the shared
929// pieces of default-engine-native-tls and default-engine-rustls. the crate can't compile with
930// _only_ default-engine-base, so we give a friendly error here.
931#[cfg(all(
932 feature = "default-engine-base",
933 not(any(
934 feature = "default-engine-native-tls",
935 feature = "default-engine-rustls",
936 ))
937))]
938compile_error!(
939 "The default-engine-base feature flag is not meant to be used directly. \
940 Please use either default-engine-native-tls or default-engine-rustls."
941);
942
943// Rustdoc's documentation tests can do some things that regular unit tests can't. Here we are
944// using doctests to test macros. Specifically, we are testing for failed macro invocations due
945// to invalid input, not the macro output when the macro invocation is successful (which can/should
946// be done in unit tests). This module is not exclusively for macro tests only so other doctests can
947// also be added. https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#include-items-only-when-collecting-doctests
948#[cfg(doctest)]
949mod doctests;