arrow_avro/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Convert data to / from the [Apache Arrow] memory format and [Apache Avro].
6//!
7//! This crate provides:
8//! - a [`reader`] that decodes Avro (Object Container Files, unframed binary datums,
9//! Avro Single‑Object encoding, and Confluent Schema Registry wire format) into Arrow
10//! `RecordBatch`es,
11//! - and a [`writer`] that encodes Arrow `RecordBatch`es into Avro (OCF or SOE).
12//!
13//! If you’re new to Arrow or Avro, see:
14//! - Arrow project site: <https://arrow.apache.org/>
15//! - Avro 1.11.1 specification: <https://avro.apache.org/docs/1.11.1/specification/>
16//!
17//! ## Example: OCF (Object Container File) round‑trip *(runnable)*
18//!
19//! The example below creates an Arrow table, writes an **Avro OCF** fully in memory,
20//! and then reads it back. OCF is a self‑describing file format that embeds the Avro
21//! schema in a header with optional compression and block sync markers.
22//! Spec: <https://avro.apache.org/docs/1.11.1/specification/#object-container-files>
23//!
24//! ```
25//! use std::io::Cursor;
26//! use std::sync::Arc;
27//! use arrow_array::{ArrayRef, Int32Array, RecordBatch};
28//! use arrow_schema::{DataType, Field, Schema};
29//! use arrow_avro::writer::AvroWriter;
30//! use arrow_avro::reader::ReaderBuilder;
31//!
32//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
33//! // Build a tiny Arrow batch
34//! let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
35//! let batch = RecordBatch::try_new(
36//! Arc::new(schema.clone()),
37//! vec![Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef],
38//! )?;
39//!
40//! // Write an Avro **Object Container File** (OCF) to a Vec<u8>
41//! let sink: Vec<u8> = Vec::new();
42//! let mut w = AvroWriter::new(sink, schema.clone())?;
43//! w.write(&batch)?;
44//! w.finish()?;
45//! let bytes = w.into_inner();
46//! assert!(!bytes.is_empty());
47//!
48//! // Read it back
49//! let mut r = ReaderBuilder::new().build(Cursor::new(bytes))?;
50//! let out = r.next().unwrap()?;
51//! assert_eq!(out.num_rows(), 3);
52//! # Ok(()) }
53//! ```
54//!
55//! ## Quickstart: unframed Avro datums *(runnable)*
56//!
57//! Kafka messages and other transports can contain bare Avro records without an OCF header,
58//! single-object prefix, or schema-registry framing. When the writer schema is already known,
59//! register it, select its fingerprint and [`reader::DecoderMode::UnframedDatum`], and call
60//! [`reader::Decoder::decode`] once per record. The returned byte count also supports
61//! consecutive datums in one buffer.
62//!
63//! ```
64//! use arrow_array::{Array, Int64Array};
65//! use arrow_avro::reader::{DecoderMode, ReaderBuilder};
66//! use arrow_avro::schema::{AvroSchema, SchemaStore};
67//!
68//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
69//! let schema = AvroSchema::new(
70//! r#"{"type":"record","name":"Event","fields":[{"name":"id","type":"long"}]}"#
71//! .to_string(),
72//! );
73//! let mut store = SchemaStore::new();
74//! let fingerprint = store.register(schema)?;
75//! let mut decoder = ReaderBuilder::new()
76//! .with_writer_schema_store(store)
77//! .with_active_fingerprint(fingerprint)
78//! .with_decoder_mode(DecoderMode::UnframedDatum)
79//! .build_decoder()?;
80//!
81//! // Two consecutive records, {id: 7} and {id: 42}, in Avro zigzag encoding.
82//! let mut remaining: &[u8] = &[0x0e, 0x54];
83//! while !remaining.is_empty() {
84//! let consumed = decoder.decode(remaining)?;
85//! remaining = &remaining[consumed..];
86//! }
87//!
88//! let batch = decoder.flush()?.expect("decoded records");
89//! let ids = batch.column(0).as_any().downcast_ref::<Int64Array>().unwrap();
90//! assert_eq!(ids.values(), &[7, 42]);
91//! # Ok(()) }
92//! ```
93//!
94//! ## Quickstart: SOE (Single‑Object Encoding) round‑trip *(runnable)*
95//!
96//! Avro **Single‑Object Encoding (SOE)** wraps an Avro body with a 2‑byte marker
97//! `0xC3 0x01` and an **8‑byte little‑endian CRC‑64‑AVRO Rabin fingerprint** of the
98//! writer schema, then the Avro body. Spec:
99//! <https://avro.apache.org/docs/1.11.1/specification/#single-object-encoding>
100//!
101//! This example registers the writer schema (computing a Rabin fingerprint), writes a
102//! single‑row Avro body (using `AvroStreamWriter`), constructs the SOE frame, and decodes it back to Arrow.
103//!
104//! ```
105//! use std::collections::HashMap;
106//! use std::sync::Arc;
107//! use arrow_array::{ArrayRef, Int64Array, RecordBatch};
108//! use arrow_schema::{DataType, Field, Schema};
109//! use arrow_avro::writer::{AvroStreamWriter, WriterBuilder};
110//! use arrow_avro::reader::ReaderBuilder;
111//! use arrow_avro::schema::{AvroSchema, SchemaStore, FingerprintStrategy, SCHEMA_METADATA_KEY};
112//!
113//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
114//! // Writer schema: { "type":"record","name":"User","fields":[{"name":"x","type":"long"}] }
115//! let writer_json = r#"{"type":"record","name":"User","fields":[{"name":"x","type":"long"}]}"#;
116//! let mut store = SchemaStore::new(); // Rabin CRC‑64‑AVRO by default
117//! let _fp = store.register(AvroSchema::new(writer_json.to_string()))?;
118//!
119//! // Build an Arrow schema that references the same Avro JSON
120//! let mut md = HashMap::new();
121//! md.insert(SCHEMA_METADATA_KEY.to_string(), writer_json.to_string());
122//! let schema = Schema::new_with_metadata(
123//! vec![Field::new("x", DataType::Int64, false)],
124//! md,
125//! );
126//!
127//! // One‑row batch: { x: 7 }
128//! let batch = RecordBatch::try_new(
129//! Arc::new(schema.clone()),
130//! vec![Arc::new(Int64Array::from(vec![7])) as ArrayRef],
131//! )?;
132//!
133//! // Stream‑write a single record; the writer adds **SOE** (C3 01 + Rabin) automatically.
134//! let sink: Vec<u8> = Vec::new();
135//! let mut w: AvroStreamWriter<Vec<u8>> = WriterBuilder::new(schema.clone())
136//! .with_fingerprint_strategy(FingerprintStrategy::Rabin)
137//! .build(sink)?;
138//! w.write(&batch)?;
139//! w.finish()?;
140//! let frame = w.into_inner(); // already: C3 01 + 8B LE Rabin + Avro body
141//! assert!(frame.len() > 10);
142//!
143//! // Decode
144//! let mut dec = ReaderBuilder::new()
145//! .with_writer_schema_store(store)
146//! .build_decoder()?;
147//! dec.decode(&frame)?;
148//! let out = dec.flush()?.expect("one row");
149//! assert_eq!(out.num_rows(), 1);
150//! # Ok(()) }
151//! ```
152//!
153//! ## `async` Reading (`async` feature)
154//!
155//! The [`reader`] module provides async APIs for reading Avro files when the `async`
156//! feature is enabled.
157//!
158//! [`AsyncAvroFileReader`] implements `Stream<Item = Result<RecordBatch, ArrowError>>`,
159//! allowing efficient async streaming of record batches. Any [`AsyncFileReader`]
160//! can be used as the source; there is a built-in implementation for types
161//! implementing [`AsyncRead`] + [`AsyncSeek`] (such as [`tokio::fs::File`]), and object
162//! storage services such as S3 can be integrated by implementing
163//! [`AsyncFileReader`] on top of a client such as the [object_store] crate
164//! (see the example on the trait documentation).
165//!
166//! [`AsyncRead`]: tokio::io::AsyncRead
167//! [`AsyncSeek`]: tokio::io::AsyncSeek
168//! [`tokio::fs::File`]: https://docs.rs/tokio/latest/tokio/fs/struct.File.html
169//!
170//! ```ignore
171//! use arrow_avro::reader::AsyncAvroFileReader;
172//! use futures::TryStreamExt;
173//!
174//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
175//! let file = tokio::fs::File::open("data/example.avro").await?;
176//! let file_size = file.metadata().await?.len();
177//!
178//! let stream = AsyncAvroFileReader::builder(file, file_size, 1024)
179//! .try_build()
180//! .await?;
181//!
182//! let batches: Vec<_> = stream.try_collect().await?;
183//! # Ok(())
184//! # }
185//! ```
186//!
187//! [object_store]: https://docs.rs/object_store/latest/object_store/
188//!
189//! ---
190//!
191//! ### Modules
192//!
193//! - [`reader`]: read Avro (OCF, unframed datums, SOE, Confluent) into Arrow `RecordBatch`es.
194//! - With the `async` feature: [`AsyncAvroFileReader`] for async streaming reads,
195//! from any [`AsyncFileReader`] source including cloud object storage.
196//! - [`writer`]: write Arrow `RecordBatch`es as Avro (OCF, SOE, Confluent, Apicurio).
197//! - [`schema`]: Avro schema parsing / fingerprints / registries.
198//! - [`compression`]: codecs used for **OCF block compression** (i.e., Deflate, Snappy, Zstandard, BZip2, and XZ).
199//! - [`codec`]: internal Avro-Arrow type conversion and row decode/encode plans.
200//!
201//! [`AsyncAvroFileReader`]: reader::AsyncAvroFileReader
202//! [`AsyncFileReader`]: reader::AsyncFileReader
203//!
204//! ### Features
205//!
206//! **OCF compression (enabled by default)**
207//! - `deflate` — enable DEFLATE block compression (via `flate2`).
208//! - `snappy` — enable Snappy block compression with 4‑byte BE CRC32 (per Avro).
209//! - `zstd` — enable Zstandard block compression.
210//! - `bzip2` — enable BZip2 block compression.
211//! - `xz` — enable XZ/LZMA block compression.
212//!
213//! **Async (opt‑in)**
214//! - `async` — enable async APIs for reading Avro (`AsyncAvroFileReader`, `AsyncFileReader` trait).
215//! Cloud storage (S3, GCS, Azure Blob, etc.) can be integrated by implementing
216//! `AsyncFileReader` on top of a client such as the [`object_store`] crate.
217//! - `object_store` (**deprecated**): enables the deprecated `AvroObjectReader`.
218//! Implement `AsyncFileReader` directly instead (see above). Implies `async`.
219//! This feature will be removed in a future release.
220//!
221//! **Schema fingerprints & helpers (opt‑in)**
222//! - `md5` — enable MD5 writer‑schema fingerprints.
223//! - `sha256` — enable SHA‑256 writer‑schema fingerprints.
224//! - `small_decimals` — support for compact Arrow representations of small Avro decimals (`Decimal32` and `Decimal64`).
225//! - `avro_custom_types` — interpret Avro fields annotated with Arrow‑specific logical
226//! types such as `arrow.duration-nanos`, `arrow.duration-micros`,
227//! `arrow.duration-millis`, or `arrow.duration-seconds` as Arrow `Duration(TimeUnit)`.
228//! - `canonical_extension_types` — enable support for Arrow [canonical extension types]
229//! from `arrow-schema` so `arrow-avro` can respect them during Avro↔Arrow mapping.
230//!
231//! **Notes**
232//! - OCF compression codecs apply only to **Object Container Files**; they do not affect Avro
233//! single object encodings.
234//!
235//! [`object_store`]: https://docs.rs/object_store/latest/object_store/
236//!
237//! [canonical extension types]: https://arrow.apache.org/docs/format/CanonicalExtensions.html
238//!
239//! [Apache Arrow]: https://arrow.apache.org/
240//! [Apache Avro]: https://avro.apache.org/
241//!
242//! # Platform Support
243//!
244//! Only little-endian platforms are officially supported and tested in CI.
245//! Big-endian platforms are not tested in CI and may not work correctly.
246//! Fixes for big-endian platforms are welcome and handled on a best-effort basis,
247//! but compatibility is not guaranteed.
248
249#![doc(
250 html_logo_url = "https://arrow.apache.org/img/arrow-logo_chevrons_black-txt_white-bg.svg",
251 html_favicon_url = "https://arrow.apache.org/img/arrow-logo_chevrons_black-txt_transparent-bg.svg"
252)]
253#![cfg_attr(docsrs, feature(doc_cfg))]
254#![warn(missing_docs)]
255
256/// Core functionality for reading Avro data into Arrow arrays
257///
258/// Implements the primary reader interface and record decoding logic.
259pub mod reader;
260
261/// Core functionality for writing Arrow arrays as Avro data
262///
263/// Implements the primary writer interface and record encoding logic.
264pub mod writer;
265
266/// Avro schema parsing and representation
267///
268/// Provides types for parsing and representing Avro schema definitions.
269pub mod schema;
270
271/// Compression codec implementations for Avro
272///
273/// Provides support for various compression algorithms used in Avro files,
274/// including Deflate, Snappy, and ZStandard.
275pub mod compression;
276
277/// Data type conversions between Avro and Arrow types
278///
279/// This module contains the necessary types and functions to convert between
280/// Avro data types and Arrow data types.
281pub mod codec;
282
283/// AvroError variants
284pub mod errors;
285
286/// Extension trait for AvroField to add Utf8View support
287///
288/// This trait adds methods for working with Utf8View support to the AvroField struct.
289pub trait AvroFieldExt {
290 /// Returns a new field with Utf8View support enabled for string data
291 ///
292 /// This will convert any string data to use StringViewArray instead of StringArray.
293 fn with_utf8view(&self) -> Self;
294}
295
296impl AvroFieldExt for codec::AvroField {
297 fn with_utf8view(&self) -> Self {
298 codec::AvroField::with_utf8view(self)
299 }
300}
301
302#[cfg(test)]
303mod test_util {
304 pub fn arrow_test_data(path: &str) -> String {
305 match std::env::var("ARROW_TEST_DATA") {
306 Ok(dir) => format!("{dir}/{path}"),
307 Err(_) => format!("../testing/data/{path}"),
308 }
309 }
310}