use std::collections::{HashMap, HashSet};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::types::{
PyAnyMethods, PyBool, PyBoolMethods, PyByteArray, PyBytes, PyDict, PyDictMethods, PyFloat,
PyFloatMethods, PyInt, PyList, PyListMethods, PyMemoryView, PyString, PyStringMethods, PyTuple,
PyType, PyTypeMethods,
};
use pyo3::{Bound, PyAny, PyErr, PyResult, Python};
use sqlload::row_batches::models::{Cell, Flatten, FlattenObjects, JsonWriter, RowColumns};
use crate::crossing::constants::{
EPOCH_ORDINAL, MICROS_PER_DAY, MICROS_PER_SECOND, NUMPY_ARRAY, NUMPY_MODULE,
};
struct Walker<'py> {
writer: JsonWriter,
datetime: Bound<'py, PyType>,
date: Bound<'py, PyType>,
time: Bound<'py, PyType>,
decimal: Bound<'py, PyType>,
utc: Bound<'py, PyAny>,
enumeration: Bound<'py, PyType>,
nonfinite_null: bool,
elements: bool,
refused: Option<f64>,
}
enum Plain<'py> {
Null,
Bool(bool),
Int(Bound<'py, PyInt>),
Float(f64),
Text(String),
Object(Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)>),
Array(Bound<'py, PyAny>),
Typed {
cell: Cell,
text: String,
},
}
#[derive(Default)]
struct FlatNames {
plain: HashSet<String>,
made: HashMap<String, String>,
}
impl FlatNames {
fn plain(&mut self, name: &str) -> PyResult<()> {
if let Some(object) = self.made.get(name) {
let key = name.strip_prefix(&format!("{object}__")).unwrap_or(name);
return Err(collision(object, key, name, "which the data already has"));
}
if !self.plain.contains(name) {
self.plain.insert(name.to_owned());
}
Ok(())
}
fn claim(&mut self, object: &str, key: &str) -> PyResult<String> {
let name = format!("{object}__{key}");
if self.plain.contains(&name) {
return Err(collision(object, key, &name, "which the data already has"));
}
match self.made.get(&name) {
Some(other) if other != object => Err(collision(
object,
key,
&name,
&format!("which flattening {other} also gives"),
)),
Some(_) => Ok(name),
None => {
self.made.insert(name.clone(), object.to_owned());
Ok(name)
}
}
}
}
fn collision(object: &str, key: &str, name: &str, clash: &str) -> PyErr {
PyValueError::new_err(format!(
"flatten {object}: the key {key} gives column {name}, {clash}; rename one of them or leave {object} unflattened"
))
}
pub(crate) fn holds_nonfinite(rows: &Bound<'_, PyList>) -> PyResult<bool> {
let walker = Walker::new(rows.py(), false)?;
for row in rows.iter() {
if walker.nonfinite(&row)? {
return Ok(true);
}
}
Ok(false)
}
pub(crate) fn walk_rows(rows: &Bound<'_, PyList>, flatten: &Flatten) -> PyResult<RowColumns> {
let mut walker = Walker::new(rows.py(), flatten.nonfinite_null)?;
let mut columns = RowColumns::new();
let mut names = FlatNames::default();
for (index, row) in rows.iter().enumerate() {
let row = row.cast::<PyDict>().map_err(|_| {
PyTypeError::new_err(format!(
"row {index} of a yielded batch is a {}, not a dict",
type_name(&row)
))
})?;
for (key, value) in row.iter() {
let key = key.cast::<PyString>().map_err(|_| key_error(&key))?;
let key = key.to_str()?;
match flatten.is_none() {
true => columns.push(
key,
walker.column_cell(&value, (key, &[key], index), flatten)?,
),
false => walker.flattened_cell(
(key, &value),
(index, &[], flatten),
(&mut columns, &mut names),
)?,
}
}
columns.end_row();
}
let mut made: Vec<String> = names.made.into_keys().collect();
made.sort();
columns.set_flattened(made);
Ok(columns)
}
impl<'py> Walker<'py> {
fn new(py: Python<'py>, nonfinite_null: bool) -> PyResult<Self> {
let datetime = py.import("datetime")?;
Ok(Self {
writer: JsonWriter::new(),
datetime: datetime.getattr("datetime")?.cast_into()?,
date: datetime.getattr("date")?.cast_into()?,
time: datetime.getattr("time")?.cast_into()?,
decimal: py.import("decimal")?.getattr("Decimal")?.cast_into()?,
utc: datetime.getattr("timezone")?.getattr("utc")?,
enumeration: py.import("enum")?.getattr("Enum")?.cast_into()?,
nonfinite_null,
elements: false,
refused: None,
})
}
fn column_cell(
&mut self,
value: &Bound<'py, PyAny>,
(name, path, row): (&str, &[&str], usize),
flatten: &Flatten,
) -> PyResult<Cell> {
self.elements = flatten.pins_array(path);
let cell = self.cell(value)?;
match self.refused.take() {
None => Ok(cell),
Some(number) => Err(PyValueError::new_err(format!(
"column {name}: row {} of a batch holds {} inside a nested value, which json can't hold; pin {name} as array(float) when it is a list of numbers, or set on_nonfinite = \"null\" to load NaN and infinities as NULL",
row + 1,
nonfinite_text(number)
))),
}
}
fn nonfinite(&self, value: &Bound<'py, PyAny>) -> PyResult<bool> {
if value.is_none() || value.is_instance_of::<PyString>() || value.is_instance_of::<PyInt>()
{
return Ok(false);
}
if let Ok(number) = value.cast::<PyFloat>() {
return Ok(!number.value().is_finite());
}
let items: Vec<Bound<'py, PyAny>> = match self.plain(value)? {
Plain::Float(number) => return Ok(!number.is_finite()),
Plain::Object(items) => items.into_iter().map(|(_, item)| item).collect(),
Plain::Array(items) => items.try_iter()?.collect::<PyResult<_>>()?,
Plain::Null | Plain::Bool(_) | Plain::Int(_) | Plain::Text(_) | Plain::Typed { .. } => {
return Ok(false);
}
};
for item in items {
if self.nonfinite(&item)? {
return Ok(true);
}
}
Ok(false)
}
fn cell(&mut self, value: &Bound<'py, PyAny>) -> PyResult<Cell> {
Ok(match self.plain(value)? {
Plain::Null => Cell::Null,
Plain::Bool(flag) => Cell::Bool(flag),
Plain::Int(number) => match number.extract::<i64>() {
Ok(number) => Cell::Int(number),
Err(_) => Cell::Number(number.str()?.to_str()?.to_owned()),
},
Plain::Float(number) => match number.is_finite() || !self.nonfinite_null {
true => Cell::Float(number),
false => Cell::Null,
},
Plain::Text(text) => Cell::Text(text),
Plain::Typed { cell, .. } => cell,
nested @ (Plain::Object(_) | Plain::Array(_)) => {
self.write(nested)?;
Cell::Json(self.writer.take())
}
})
}
fn value(&mut self, value: &Bound<'py, PyAny>) -> PyResult<()> {
let plain = self.plain(value)?;
self.write(plain)
}
fn write(&mut self, plain: Plain<'py>) -> PyResult<()> {
match plain {
Plain::Null => self.writer.raw("null"),
Plain::Bool(flag) => self.writer.raw(if flag { "true" } else { "false" }),
Plain::Int(number) => match number.extract::<i64>() {
Ok(number) => self.writer.raw(&number.to_string()),
Err(_) => self.writer.raw(number.str()?.to_str()?),
},
Plain::Float(number) if number.is_finite() => self.writer.float(number),
Plain::Float(number) => match (self.nonfinite_null, self.elements) {
(true, _) => self.writer.raw("null"),
(false, true) => self.writer.string(nonfinite_text(number)),
(false, false) => {
self.refused.get_or_insert(number);
self.writer.raw("null");
}
},
Plain::Text(text) | Plain::Typed { text, .. } => self.writer.string(&text),
Plain::Object(items) => {
self.writer.raw("{");
for (position, (key, item)) in items.iter().enumerate() {
let key = key.cast::<PyString>().map_err(|_| key_error(key))?;
if position > 0 {
self.writer.raw(",");
}
self.writer.string(key.to_str()?);
self.writer.raw(":");
self.value(item)?;
}
self.writer.raw("}");
}
Plain::Array(items) => {
self.writer.raw("[");
for (position, item) in items.try_iter()?.enumerate() {
if position > 0 {
self.writer.raw(",");
}
self.value(&item?)?;
}
self.writer.raw("]");
}
}
Ok(())
}
fn plain(&self, value: &Bound<'py, PyAny>) -> PyResult<Plain<'py>> {
if value.is_none() {
return Ok(Plain::Null);
}
if let Ok(text) = value.cast::<PyString>() {
return Ok(Plain::Text(text.to_str()?.to_owned()));
}
if let Ok(flag) = value.cast_exact::<PyBool>() {
return Ok(Plain::Bool(flag.is_true()));
}
if let Ok(number) = value.cast::<PyInt>() {
return Ok(Plain::Int(number.clone()));
}
if let Ok(number) = value.cast_exact::<PyFloat>() {
return Ok(Plain::Float(number.value()));
}
if let Ok(object) = value.cast::<PyDict>() {
return Ok(Plain::Object(object.iter().collect()));
}
let bytes = if value.is_instance_of::<PyBytes>() || value.is_instance_of::<PyByteArray>() {
Some(value.extract::<Vec<u8>>()?)
} else if value.is_instance_of::<PyMemoryView>() {
Some(value.call_method0("tobytes")?.extract::<Vec<u8>>()?)
} else {
None
};
if let Some(bytes) = bytes {
return Ok(Plain::Typed {
text: STANDARD.encode(&bytes),
cell: Cell::Binary(bytes),
});
}
if value.is_instance_of::<PyList>() || value.is_exact_instance_of::<PyTuple>() {
return Ok(Plain::Array(value.clone()));
}
let kind = value.get_type();
if kind.is(&self.datetime) {
return self.moment(value);
}
if kind.is(&self.date) {
return Ok(Plain::Typed {
cell: Cell::Date(i32::try_from(epoch_days(value)?).unwrap_or(i32::MAX)),
text: iso_text(value)?,
});
}
if kind.is(&self.time) {
return Ok(Plain::Text(iso_text(value)?));
}
if value.is_instance(&self.decimal)? {
let text = value.str()?.to_str()?.to_owned();
return Ok(match value.call_method0("is_finite")?.is_truthy()? {
true => Plain::Typed {
cell: Cell::Decimal(
value
.call_method1("__format__", ("f",))?
.str()?
.to_str()?
.to_owned(),
),
text,
},
false => Plain::Typed {
cell: Cell::Null,
text,
},
});
}
if value.is_instance(&self.enumeration)? {
return self.plain(&value.getattr("value")?);
}
if kind.hasattr("__dataclass_fields__")? {
return dataclass_fields(value).map(Plain::Object);
}
if kind.module()?.to_str()? == NUMPY_MODULE {
return numpy_plain(value);
}
Ok(Plain::Text(value.str()?.to_str()?.to_owned()))
}
}
impl<'py> Walker<'py> {
fn flattened_cell(
&mut self,
(key, value): (&str, &Bound<'py, PyAny>),
(row, path, flatten): (usize, &[String], &Flatten),
(columns, names): (&mut RowColumns, &mut FlatNames),
) -> PyResult<()> {
let here: Vec<&str> = path.iter().map(String::as_str).chain([key]).collect();
let object = flatten.lists(&here)
|| (flatten.objects == FlattenObjects::All && value.is_instance_of::<PyDict>());
if !(object && flatten.flattens(&here).map_err(PyValueError::new_err)?) {
if path.is_empty() {
names.plain(key)?;
columns.push(key, self.column_cell(value, (key, &here, row), flatten)?);
} else if !value.is_none() {
let name = names.claim(&path.join("__"), key)?;
let cell = self.column_cell(value, (&name, &here, row), flatten)?;
columns.push(&name, cell);
}
return Ok(());
}
let items = match self.plain(value)? {
Plain::Null => return Ok(()),
Plain::Object(items) => items,
other => {
let listed = here.join(".");
return Err(PyValueError::new_err(format!(
"flatten {listed}: row {} of a batch holds {}, not an object; the shape changed, so leave {listed} unflattened or fix the source",
row + 1,
shape(&other)
)));
}
};
let below: Vec<String> = here.iter().map(|part| (*part).to_owned()).collect();
for (item_key, item) in items {
let item_key = item_key
.cast::<PyString>()
.map_err(|_| key_error(&item_key))?;
self.flattened_cell(
(item_key.to_str()?, &item),
(row, &below, flatten),
(columns, names),
)?;
}
Ok(())
}
fn moment(&self, value: &Bound<'py, PyAny>) -> PyResult<Plain<'py>> {
let text = iso_text(value)?;
if !value.call_method0("utcoffset")?.is_none() {
let utc = value.call_method1("astimezone", (&self.utc,))?;
return Ok(Plain::Typed {
cell: Cell::Text(iso_text(&utc)?),
text,
});
}
let field = |name: &str| -> PyResult<i64> { value.getattr(name)?.extract::<i64>() };
let seconds = field("hour")? * 3_600 + field("minute")? * 60 + field("second")?;
let micros = epoch_days(value)? * MICROS_PER_DAY
+ seconds * MICROS_PER_SECOND
+ field("microsecond")?;
Ok(Plain::Typed {
cell: Cell::TimestampNtz(micros),
text,
})
}
}
fn epoch_days(value: &Bound<'_, PyAny>) -> PyResult<i64> {
Ok(value.call_method0("toordinal")?.extract::<i64>()? - EPOCH_ORDINAL)
}
fn iso_text(value: &Bound<'_, PyAny>) -> PyResult<String> {
Ok(value.call_method0("isoformat")?.str()?.to_str()?.to_owned())
}
fn dataclass_fields<'py>(
value: &Bound<'py, PyAny>,
) -> PyResult<Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)>> {
let attributes: Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)> = match value.getattr("__dict__") {
Ok(attributes) => attributes.cast_into::<PyDict>()?.iter().collect(),
Err(_) => value
.py()
.import("dataclasses")?
.call_method1("fields", (value,))?
.try_iter()?
.map(|field| {
let name = field?.getattr("name")?.cast_into::<PyString>()?;
let item = value.getattr(&name)?;
Ok((name.into_any(), item))
})
.collect::<PyResult<_>>()?,
};
let mut fields = Vec::with_capacity(attributes.len());
for (name, item) in attributes {
let public = match name.cast::<PyString>() {
Ok(text) => !text.to_str()?.starts_with('_'),
Err(_) => true,
};
if public {
fields.push((name, item));
}
}
Ok(fields)
}
fn numpy_plain<'py>(value: &Bound<'py, PyAny>) -> PyResult<Plain<'py>> {
let dtype = value.getattr("dtype")?;
let kind = dtype.getattr("kind")?.str()?.to_str()?.to_owned();
if value.get_type().name()?.to_str()? == NUMPY_ARRAY {
let numeric = matches!(kind.as_str(), "b" | "i" | "u" | "f");
return Ok(
match numeric && value.getattr("ndim")?.extract::<usize>()? > 0 {
true => Plain::Array(value.clone()),
false => Plain::Text(value.str()?.to_str()?.to_owned()),
},
);
}
let size = dtype.getattr("itemsize")?.extract::<usize>()?;
Ok(match (kind.as_str(), size) {
("b", _) => Plain::Bool(value.call_method0("item")?.is_truthy()?),
("i" | "u", _) => Plain::Int(value.call_method0("item")?.cast_into::<PyInt>()?),
("f", 8) => Plain::Float(value.call_method0("item")?.extract::<f64>()?),
("f", 2 | 4) => {
let single = value.call_method1("astype", ("float32",))?.str()?;
Plain::Float(single.to_str()?.parse::<f64>().unwrap_or(f64::NAN))
}
("M", _) => {
let micros = value
.call_method1("astype", ("datetime64[us]",))?
.call_method0("item")?;
match micros.is_none() {
true => Plain::Null,
false => Plain::Text(
micros
.call_method0("isoformat")?
.str()?
.to_str()?
.to_owned(),
),
}
}
_ => Plain::Text(value.str()?.to_str()?.to_owned()),
})
}
fn nonfinite_text(number: f64) -> &'static str {
match (number.is_nan(), number.is_sign_negative()) {
(true, _) => "NaN",
(false, false) => "inf",
(false, true) => "-inf",
}
}
fn shape(plain: &Plain<'_>) -> &'static str {
match plain {
Plain::Null | Plain::Object(_) => "an object",
Plain::Bool(_) => "a boolean",
Plain::Int(_) | Plain::Float(_) => "a number",
Plain::Text(_) => "a text value",
Plain::Array(_) => "a list",
Plain::Typed {
cell: Cell::Date(_),
..
} => "a date",
Plain::Typed {
cell: Cell::Decimal(_) | Cell::Null,
..
} => "a decimal",
Plain::Typed {
cell: Cell::Binary(_),
..
} => "bytes",
Plain::Typed { .. } => "a timestamp",
}
}
fn key_error(key: &Bound<'_, PyAny>) -> PyErr {
PyTypeError::new_err(format!("dict keys must be str, not {}", type_name(key)))
}
fn type_name(value: &Bound<'_, PyAny>) -> String {
value
.get_type()
.name()
.map_or_else(|_| "object".to_owned(), |name| name.to_string())
}