sqlload-python-host 0.89.0

The Python host of SQLLoad's engine: runs Python tables and crosses what they yield into the engine, for a pyo3 extension of your own.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
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,
};

/// Reads Python values by orjson's rules (`OPT_SERIALIZE_NUMPY`, `default=str`), except that a top-level `Decimal`, `date` or `datetime` keeps its type.
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>,
    /// `on_nonfinite = "null"`: NaN and infinite floats read as NULL.
    nonfinite_null: bool,
    /// Whether the column being read is pinned as an array, whose NaN and infinite elements cross as their text.
    elements: bool,
    /// The first NaN or infinite float written inside the nested value being read, which JSON can't hold.
    refused: Option<f64>,
}

/// One Python value as orjson sees it.
enum Plain<'py> {
    Null,
    Bool(bool),
    Int(Bound<'py, PyInt>),
    Float(f64),
    Text(String),
    /// A dict's items, or a dataclass's public fields.
    Object(Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)>),
    /// A list, tuple or numeric numpy array.
    Array(Bound<'py, PyAny>),
    /// A `Decimal`, `date` or `datetime`: its typed cell at the top of a row, and its text (as orjson writes it) inside a nested value.
    Typed {
        cell: Cell,
        text: String,
    },
}

/// The columns flattening made in one batch, by the object each came from, and the batch's other columns, so no name comes from two places.
#[derive(Default)]
struct FlatNames {
    plain: HashSet<String>,
    made: HashMap<String, String>,
}

impl FlatNames {
    /// Note a column of the rows themselves; an error when flattening already made it.
    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(())
    }

    /// Claim `<object>__<key>` for `object`; an error when a column of the rows or another object already gives it.
    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"
    ))
}

/// Whether any value of `rows`, a list of dicts, is or holds a NaN or infinite float, which orjson writes as `null`.
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)
}

/// Read `rows`, a list of dicts, column by column, holding the GIL; each dict `flatten` flattens becomes one typed column per key, `<object>__<key>`, and its dicts in turn.
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,
        })
    }

    /// The cell for `value` in column `name`, at `path` (keys from the row down) in row `row` of the batch: a NaN or infinite float inside a nested value fails it, as `json` can't hold one, unless the column is pinned as an array, whose elements keep it, or `on_nonfinite = "null"` reads it as NULL.
    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)
            ))),
        }
    }

    /// Whether `value` is or holds a NaN or infinite float, read as [`Walker::plain`] reads it.
    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)
    }

    /// The cell for one Python value: a `Decimal` as a decimal, a `date` as a date, a naive `datetime` as `timestamp_ntz` and an aware one as UTC RFC 3339 text (`timestamp_tz`), a float as a float, NaN and infinities included (NULL under `on_nonfinite = "null"`); anything else as orjson would write it, then read back (times are ISO text; unknown types are `str()`).
    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())
            }
        })
    }

    /// Append `value` to the JSON text, keys in dict order, as orjson writes it.
    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(())
    }

    /// What orjson makes of `value`: str, int, dict and list subclasses as their base type; exact floats, tuples and dates; enums as their values; dataclasses as objects; numpy numbers; anything else as `str()`.
    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> {
    /// Push `value` under `key`, at `path` below the row, or, when it is a dict `flatten` flattens (a listed path, or under `"all"` any dict), its items in its place, named `<object>__<key>`, and theirs in turn: nothing for `None` there or inside a flattened dict, and an error for a listed path holding anything but a dict.
    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(())
    }

    /// A `datetime`: naive as `timestamp_ntz` microseconds on the wall clock, aware as UTC RFC 3339 text.
    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,
        })
    }
}

/// Days from 1970-01-01 to the date of `value`, a `date` or `datetime`.
fn epoch_days(value: &Bound<'_, PyAny>) -> PyResult<i64> {
    Ok(value.call_method0("toordinal")?.extract::<i64>()? - EPOCH_ORDINAL)
}

/// `value.isoformat()`.
fn iso_text(value: &Bound<'_, PyAny>) -> PyResult<String> {
    Ok(value.call_method0("isoformat")?.str()?.to_str()?.to_owned())
}

/// A dataclass's attributes as orjson writes them: `__dict__`, or the fields of a slotted one, without names starting `_`.
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)
}

/// A numpy scalar or array as orjson's `OPT_SERIALIZE_NUMPY` writes it: numbers and booleans as JSON ones, datetimes as ISO text, numeric arrays as lists.
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()),
    })
}

/// A NaN or infinite float as text a float column reads back: `NaN`, `inf` or `-inf`.
fn nonfinite_text(number: f64) -> &'static str {
    match (number.is_nan(), number.is_sign_negative()) {
        (true, _) => "NaN",
        (false, false) => "inf",
        (false, true) => "-inf",
    }
}

/// A value's shape in words, for a listed object that holds something else.
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())
}