use std::any::Any;
use std::collections::HashMap;
use std::io::Write;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::sync::Arc;
use arrow::array::{ArrayRef, RecordBatch, StringBuilder};
use arrow::datatypes::{DataType, Field, Schema as ArrowSchema, SchemaRef};
use super::serialize::ArrowSerialize;
use super::METADATA_KEY;
use crate::encode::{
json::serialize::to_json_in_buf, DbnEncodable, EncodeDbn, EncodeRecord, EncodeRecordRef,
EncodeRecordTextExt,
};
use crate::{
rtype_dispatch, schema_dispatch, v3, Compression, Error, Metadata, RecordRef, Result, Schema,
DBN_VERSION,
};
pub struct Encoder<B: ColumnarWriter> {
writer: Option<B>,
schema: SchemaRef,
rows: Box<dyn Rows>,
symbol: Option<StringBuilder>,
pretty_px: bool,
batch_size: usize,
}
pub struct EncoderBuilder<B: ColumnarWriter> {
writer: B::Inner,
batch_size: NonZeroUsize,
pretty_px: bool,
with_symbol: bool,
compression: Compression,
metadata: HashMap<String, String>,
schema: Option<Schema>,
ts_out: bool,
version: u8,
_format: PhantomData<B>,
}
impl<B: ColumnarWriter> EncoderBuilder<B> {
pub fn new(writer: B::Inner) -> Self {
Self {
writer,
batch_size: DEFAULT_BATCH_SIZE,
pretty_px: false,
with_symbol: false,
compression: Compression::None,
metadata: HashMap::new(),
schema: None,
ts_out: false,
version: DBN_VERSION,
_format: PhantomData,
}
}
pub fn batch_size(mut self, size: NonZeroUsize) -> Self {
self.batch_size = size;
self
}
pub fn pretty_px(mut self, pretty_px: bool) -> Self {
self.pretty_px = pretty_px;
self
}
pub fn with_symbol(mut self, with_symbol: bool) -> Self {
self.with_symbol = with_symbol;
self
}
pub fn compression(mut self, compression: Compression) -> Self {
self.compression = compression;
self
}
pub fn metadata(mut self, metadata: &Metadata) -> Self {
let mut json = String::new();
to_json_in_buf(&mut json, metadata, false, false, false);
json.pop();
self.metadata = HashMap::from([(METADATA_KEY.to_owned(), json)]);
self.schema = metadata.schema;
self.ts_out = metadata.ts_out;
self.version = metadata.version;
self
}
pub fn schema(mut self, schema: Schema) -> Self {
self.schema = Some(schema);
self
}
pub fn ts_out(mut self, ts_out: bool) -> Self {
self.ts_out = ts_out;
self
}
pub fn version(mut self, version: u8) -> Self {
self.version = version;
self
}
pub fn build(self) -> Result<Encoder<B>> {
let Some(schema) = self.schema else {
return Err(Error::encode(
"can't encode columnar format with mixed schemas; a single schema is required",
));
};
let batch_size = self.batch_size.get();
let (mut fields, rows) = schema_dispatch!(
schema,
version: self.version,
ts_out: self.ts_out,
rows_for(self.pretty_px, batch_size)
);
let symbol = self.with_symbol.then(|| {
fields.push(Field::new("symbol", DataType::Utf8, true));
StringBuilder::with_capacity(batch_size, 0)
});
let schema = Arc::new(ArrowSchema::new_with_metadata(fields, self.metadata));
let writer = B::open(self.writer, schema.clone(), self.compression)?;
Ok(Encoder {
writer: Some(writer),
schema,
rows,
symbol,
pretty_px: self.pretty_px,
batch_size,
})
}
}
impl<B: ColumnarWriter> Encoder<B> {
pub fn builder(writer: B::Inner) -> EncoderBuilder<B> {
EncoderBuilder::new(writer)
}
pub fn is_closed(&self) -> bool {
self.writer.is_none()
}
pub fn close(&mut self) -> Result<()> {
let Some(mut writer) = self.writer.take() else {
return Ok(());
};
if self.rows.len() > 0 {
writer.write(&self.finish_batch()?)?;
}
writer.close()
}
fn writer(&mut self) -> Result<&mut B> {
self.writer
.as_mut()
.ok_or_else(|| Error::encode("columnar encoder has already been closed"))
}
fn append(
&mut self,
record: &dyn Any,
type_name: &str,
symbol: Option<Option<&str>>,
) -> Result<()> {
self.writer()?;
self.rows.push(record, type_name)?;
if let Some(symbol) = symbol {
self.symbol
.as_mut()
.expect("symbol column checked by caller")
.append_option(symbol);
}
if self.rows.len() >= self.batch_size {
let batch = self.finish_batch()?;
self.writer()?.write(&batch)?;
}
Ok(())
}
fn finish_batch(&mut self) -> Result<RecordBatch> {
let mut columns = Vec::with_capacity(self.schema.fields().len());
self.rows.take_columns(self.pretty_px, &mut columns);
if let Some(symbol) = &mut self.symbol {
columns.push(Arc::new(symbol.finish()));
}
RecordBatch::try_new(self.schema.clone(), columns)
.map_err(|e| Error::arrow(e, "finishing Arrow batch"))
}
fn encode_with_ts_out<R: DbnEncodable + v3::HasRType + crate::RecordMut + Clone>(
&mut self,
rec: &R,
ts_out: u64,
) -> Result<()> {
self.encode_record(&crate::WithTsOut::new(rec.clone(), ts_out))
}
}
impl<B: ColumnarWriter> EncodeRecord for Encoder<B> {
fn encode_record<R: DbnEncodable>(&mut self, record: &R) -> Result<()> {
if self.symbol.is_some() {
return Err(Error::encode(
"Encoder configured with with_symbol(true); use encode_record_with_sym",
));
}
self.append(record, std::any::type_name::<R>(), None)
}
fn flush(&mut self) -> Result<()> {
if self.rows.len() > 0 {
let batch = self.finish_batch()?;
self.writer()?.write(&batch)?;
}
self.writer()?.flush()
}
}
impl<B: ColumnarWriter> EncodeRecordRef for Encoder<B> {
fn encode_record_ref(&mut self, record: RecordRef) -> Result<()> {
if self.symbol.is_some() {
return Err(Error::encode(
"Encoder configured with with_symbol(true); use encode_ref_with_sym",
));
}
rtype_dispatch!(record, self.encode_record())?
}
unsafe fn encode_record_ref_ts_out(&mut self, record: RecordRef, ts_out: bool) -> Result<()> {
rtype_dispatch!(record, ts_out: ts_out, self.encode_record())?
}
fn encode_record_ref_with_ts_out(&mut self, record: RecordRef, ts_out: u64) -> Result<()> {
rtype_dispatch!(record, self.encode_with_ts_out(ts_out))?
}
}
impl<B: ColumnarWriter> EncodeDbn for Encoder<B> {}
impl<B: ColumnarWriter> EncodeRecordTextExt for Encoder<B> {
fn encode_record_with_sym<R: DbnEncodable>(
&mut self,
record: &R,
symbol: Option<&str>,
) -> Result<()> {
if self.symbol.is_none() {
return Err(Error::encode(
"Encoder not configured with with_symbol(true); use encode_record",
));
}
self.append(record, std::any::type_name::<R>(), Some(symbol))
}
}
impl<B: ColumnarWriter> Drop for Encoder<B> {
fn drop(&mut self) {
let _ = self.close();
}
}
pub(crate) const DEFAULT_BATCH_SIZE: NonZeroUsize = NonZeroUsize::new(65_536).unwrap();
pub trait ColumnarWriter: Sized {
type Inner: Write + Send;
fn open(writer: Self::Inner, schema: SchemaRef, compression: Compression) -> Result<Self>;
fn write(&mut self, batch: &RecordBatch) -> Result<()>;
fn flush(&mut self) -> Result<()>;
fn close(self) -> Result<()>;
}
trait Rows: Send {
fn push(&mut self, record: &dyn Any, type_name: &str) -> Result<()>;
fn len(&self) -> usize;
fn take_columns(&mut self, pretty_px: bool, out: &mut Vec<ArrayRef>);
}
struct TypedRows<R>(Vec<R>);
impl<R> Rows for TypedRows<R>
where
R: ArrowSerialize + v3::HasRType + Clone + Send + 'static,
{
fn push(&mut self, record: &dyn Any, type_name: &str) -> Result<()> {
let Some(record) = record.downcast_ref::<R>() else {
return Err(Error::encode(format!(
"expected {} records, but found {type_name}. Mixed schemas cannot be encoded \
in Parquet or Arrow",
std::any::type_name::<R>(),
)));
};
self.0.push(record.clone());
Ok(())
}
fn len(&self) -> usize {
self.0.len()
}
fn take_columns(&mut self, pretty_px: bool, out: &mut Vec<ArrayRef>) {
R::arrow_columns(&self.0, |r| r, pretty_px, out);
self.0.clear();
}
}
fn rows_for<R>(pretty_px: bool, capacity: usize) -> (Vec<Field>, Box<dyn Rows>)
where
R: ArrowSerialize + v3::HasRType + Clone + Send + 'static,
{
let mut fields = Vec::new();
R::arrow_fields(pretty_px, &mut fields);
(
fields,
Box::new(TypedRows::<R>(Vec::with_capacity(capacity))),
)
}