fv-value-datafusion 0.3.0

The fv-value expression dialect as DataFusion expressions: exact translation for pushdown and vectorized evaluation, with a per-row UDF fallback.
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Arrow ↔ [`Value`] conversion for the per-row fallback.

use std::sync::Arc;

use datafusion::arrow::array::{Array, ArrayRef, AsArray, BooleanArray, Float64Array, NullArray, StringArray};
use datafusion::arrow::datatypes::{
    DataType, Field, Float16Type, Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
    UInt32Type, UInt64Type, UInt8Type,
};
use datafusion::error::{DataFusionError, Result};
use fv_value::Value;
use geo_traits::{
    CoordTrait, Dimensions, GeometryCollectionTrait, GeometryTrait, GeometryType, LineStringTrait,
    MultiLineStringTrait, MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait,
};

/// Whether a value of Arrow type `t` has an exact form in the dialect: every number, string and
/// boolean type (a dictionary of them reads as its values), lists of such values, and structs of
/// them (as objects). Anything else — binary, decimal, temporal, map — has none, and is refused
/// by name rather than read as a value it is not.
pub fn has_value_form(t: &DataType) -> bool {
    match t {
        DataType::Null
        | DataType::Boolean
        | DataType::Int8
        | DataType::Int16
        | DataType::Int32
        | DataType::Int64
        | DataType::UInt8
        | DataType::UInt16
        | DataType::UInt32
        | DataType::UInt64
        | DataType::Float16
        | DataType::Float32
        | DataType::Float64
        | DataType::Utf8
        | DataType::LargeUtf8
        | DataType::Utf8View => true,
        DataType::Dictionary(_, values) => has_value_form(values),
        DataType::List(f) | DataType::LargeList(f) | DataType::FixedSizeList(f, _) => has_value_form(f.data_type()),
        DataType::Struct(fields) => fields.iter().all(|f| has_value_form(f.data_type())),
        _ => false,
    }
}

/// The GeoArrow extension a field carries, read as the dialect's geometry forms.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Geo {
    /// `geoarrow.point`, separated (`Struct<x, y[, z][, m]>`) or interleaved
    /// (`FixedSizeList<Float64>`): the dialect's point `[x, y]`, or `[x, y, z]` with an altitude.
    Point,
    /// `geoarrow.wkb` (or GDAL's `ogc.wkb`): the geometry as a GeoJSON object.
    Wkb,
}

/// The geometry a field holds, from its `ARROW:extension:name`, when its type fits it.
fn geo_of(field: &Field) -> Option<Geo> {
    let name = field.metadata().get("ARROW:extension:name")?;
    match (name.as_str(), field.data_type()) {
        ("geoarrow.point", DataType::Struct(fs))
            if fs.len() >= 2 && fs.iter().all(|f| f.data_type() == &DataType::Float64) =>
        {
            Some(Geo::Point)
        }
        ("geoarrow.point", DataType::FixedSizeList(f, 2..=4)) if f.data_type() == &DataType::Float64 => {
            Some(Geo::Point)
        }
        ("geoarrow.wkb" | "ogc.wkb", DataType::Binary | DataType::LargeBinary | DataType::BinaryView) => Some(Geo::Wkb),
        _ => None,
    }
}

/// Whether `field` is a GeoArrow point or WKB column.
pub(crate) fn is_geoarrow(field: &Field) -> bool {
    geo_of(field).is_some()
}

/// Whether `field` is a GeoArrow WKB column, which can hold polygons.
pub(crate) fn is_geoarrow_wkb(field: &Field) -> bool {
    geo_of(field) == Some(Geo::Wkb)
}

/// [`has_value_form`] for a field: also a GeoArrow point or WKB column, which reads as the
/// dialect's geometry forms.
pub fn field_has_value_form(field: &Field) -> bool {
    geo_of(field).is_some() || has_value_form(field.data_type())
}

/// One cell of an Arrow array as a dialect [`Value`]: every numeric width becomes `Num`, every
/// string flavour `Str`, booleans `Bool`, a dictionary its value, lists `List` and structs `Obj`
/// (recursively). A type with no form in the dialect ([`has_value_form`]) is an error, never a
/// value it is not.
pub fn cell_to_value(array: &ArrayRef, i: usize) -> Result<Value> {
    Ok(Cells::of(array)?.value(i))
}

/// A column read as dialect values, its type checked once: each cell then reads with no error
/// path. What a caller converting whole batches uses (`cell_to_value` checks the type per cell).
#[derive(Clone, Copy, Debug)]
pub struct Cells<'a> {
    array: &'a ArrayRef,
    geo: Option<Geo>,
}

impl<'a> Cells<'a> {
    /// The column, if its type has a value in the dialect ([`has_value_form`]).
    pub fn of(array: &'a ArrayRef) -> Result<Self> {
        if has_value_form(array.data_type()) {
            Ok(Cells { array, geo: None })
        } else {
            Err(DataFusionError::Execution(format!(
                "fv-value: a {} value has no form in the dialect",
                array.data_type()
            )))
        }
    }

    /// The column of `field`, read by its type as [`of`](Cells::of) reads it, or by its GeoArrow
    /// extension: a `geoarrow.point` row is the point `[x, y]` (with `z`, `[x, y, z]`), and a
    /// `geoarrow.wkb` or `ogc.wkb` row is its geometry as a GeoJSON object, or null when its bytes
    /// are not WKB.
    pub fn of_field(field: &Field, array: &'a ArrayRef) -> Result<Self> {
        match geo_of(field) {
            Some(geo) => Ok(Cells { array, geo: Some(geo) }),
            None => Cells::of(array),
        }
    }

    /// Row `i` as a dialect value.
    #[inline]
    pub fn value(&self, i: usize) -> Value {
        match self.geo {
            None => value_at(self.array, i),
            Some(_) if self.array.is_null(i) => Value::Null,
            Some(Geo::Point) => point_at(self.array, i),
            Some(Geo::Wkb) => wkb_at(self.array, i),
        }
    }
}

/// A GeoArrow point as `[x, y]`, or `[x, y, z]` when it has a `z`; an `m` is not a coordinate.
fn point_at(array: &ArrayRef, i: usize) -> Value {
    let coords: Vec<f64> = match array.data_type() {
        DataType::Struct(fields) => {
            let s = array.as_struct();
            fields
                .iter()
                .zip(s.columns())
                .filter(|(f, _)| f.name() != "m")
                .map(|(_, c)| c.as_primitive::<Float64Type>().value(i))
                .collect()
        }
        DataType::FixedSizeList(f, n) => {
            let xs = array.as_fixed_size_list().value(i);
            let xs = xs.as_primitive::<Float64Type>();
            // an interleaved point's last value is its m when the child is named for one (xym, xyzm)
            let take = if f.name().ends_with('m') {
                *n as usize - 1
            } else {
                *n as usize
            };
            xs.values()[..take].to_vec()
        }
        _ => return Value::Null,
    };
    Value::List(coords.into_iter().map(Value::Num).collect())
}

/// A WKB geometry as a GeoJSON object, with its altitude, or null when the bytes are not WKB.
fn wkb_at(array: &ArrayRef, i: usize) -> Value {
    let bytes: &[u8] = match array.data_type() {
        DataType::Binary => array.as_binary::<i32>().value(i),
        DataType::LargeBinary => array.as_binary::<i64>().value(i),
        DataType::BinaryView => array.as_binary_view().value(i),
        _ => return Value::Null,
    };
    wkb::reader::read_wkb(bytes)
        .ok()
        .and_then(|g| geojson_of(&g))
        .map_or(Value::Null, |j| fv_value::json_to_value(&j))
}

/// A WKB geometry's header, read in place: its byte order, its type (1 a point, 3 a polygon, 6 a
/// multipolygon), the values a position holds (2, or 3 with a z), and where its body starts.
#[derive(Clone, Copy)]
struct Header {
    le: bool,
    ty: u32,
    dim: usize,
    at: usize,
}

/// The header of the WKB in `b`, or `None` for bytes that are not WKB or a geometry with an m.
/// ISO adds 1000 to the type for a z; EWKB flags a z, an m and an SRID in the high bits.
#[inline]
fn header(b: &[u8]) -> Option<Header> {
    let le = match *b.first()? {
        1 => true,
        0 => false,
        _ => return None,
    };
    let raw = u32_at(b, 1, le)?;
    let (ty, z) = match (raw & 0x0FFF_FFFF, raw & 0xC000_0000) {
        (t @ 1..=7, 0) => (t, false),
        (t @ 1001..=1007, 0) => (t - 1000, true),
        (t @ 1..=7, 0x8000_0000) => (t, true),
        _ => return None,
    };
    Some(Header {
        le,
        ty,
        dim: if z { 3 } else { 2 },
        at: if raw & 0x2000_0000 != 0 { 9 } else { 5 },
    })
}

#[inline]
fn u32_at(b: &[u8], at: usize, le: bool) -> Option<u32> {
    let w: [u8; 4] = b.get(at..at.checked_add(4)?)?.try_into().ok()?;
    Some(if le {
        u32::from_le_bytes(w)
    } else {
        u32::from_be_bytes(w)
    })
}

/// The number at `at`, which the caller has checked lies within `b`.
#[inline]
fn f64_at(b: &[u8], at: usize, le: bool) -> f64 {
    let w: [u8; 8] = b[at..at + 8].try_into().unwrap();
    if le {
        f64::from_le_bytes(w)
    } else {
        f64::from_be_bytes(w)
    }
}

/// A WKB point's x, y, and z when it has one, read in place: ISO or EWKB, either byte order, with
/// or without an SRID. `None` for any other geometry or a point with an m: the dialect answers
/// those, through the full WKB reader.
#[inline]
pub(crate) fn wkb_point(b: &[u8]) -> Option<(f64, f64, Option<f64>)> {
    let h = header(b)?;
    if h.ty != 1 || b.len() != h.at + 8 * h.dim {
        return None;
    }
    let f = |k: usize| f64_at(b, h.at + 8 * k, h.le);
    Some((f(0), f(1), (h.dim == 3).then(|| f(2))))
}

/// A WKB polygon's or multipolygon's polygons, read in place: each its rings, each its positions.
/// `None` for any other geometry, a position with an m, or bytes that do not hold exactly one: the
/// dialect answers those, through the full WKB reader. Every length is checked here, once.
pub(crate) fn wkb_polygons(b: &[u8]) -> Option<WkbPolygons<'_>> {
    let h = header(b)?;
    let (count, rest) = match h.ty {
        3 => (1, b),
        6 => (u32_at(b, h.at, h.le)?, b.get(h.at + 4..)?),
        _ => return None,
    };
    let mut at = 0;
    for _ in 0..count {
        let part = header(rest.get(at..)?)?;
        if part.ty != 3 {
            return None;
        }
        at += part.at + polygon_len(rest.get(at + part.at..)?, part)?;
    }
    (at == rest.len()).then_some(WkbPolygons { left: count, rest })
}

/// The bytes a polygon's body takes (its ring count, then each ring's count and positions), or
/// `None` when they run past the end.
fn polygon_len(b: &[u8], h: Header) -> Option<usize> {
    let rings = u32_at(b, 0, h.le)?;
    let mut at = 4usize;
    for _ in 0..rings {
        let n = u32_at(b, at, h.le)? as usize;
        at = at.checked_add(4)?.checked_add(n.checked_mul(8 * h.dim)?)?;
        if at > b.len() {
            return None;
        }
    }
    Some(at)
}

/// The polygons of a WKB polygon or multipolygon, each read as it is reached.
pub(crate) struct WkbPolygons<'a> {
    left: u32,
    rest: &'a [u8],
}

impl<'a> Iterator for WkbPolygons<'a> {
    type Item = WkbRings<'a>;

    #[inline]
    fn next(&mut self) -> Option<WkbRings<'a>> {
        // the lengths were checked when this was made
        self.left = self.left.checked_sub(1)?;
        let h = header(self.rest)?;
        let body = &self.rest[h.at..];
        let len = polygon_len(body, h)?;
        self.rest = &body[len..];
        Some(WkbRings {
            le: h.le,
            dim: h.dim,
            left: u32_at(body, 0, h.le)?,
            rest: &body[4..len],
        })
    }
}

/// A WKB polygon's rings, each read as it is reached.
pub(crate) struct WkbRings<'a> {
    le: bool,
    dim: usize,
    left: u32,
    rest: &'a [u8],
}

impl<'a> Iterator for WkbRings<'a> {
    type Item = WkbPositions<'a>;

    #[inline]
    fn next(&mut self) -> Option<WkbPositions<'a>> {
        self.left = self.left.checked_sub(1)?;
        let n = u32_at(self.rest, 0, self.le)? as usize;
        let (ring, rest) = self.rest[4..].split_at(n * 8 * self.dim);
        self.rest = rest;
        Some(WkbPositions {
            le: self.le,
            step: 8 * self.dim,
            bytes: ring,
        })
    }
}

/// A WKB ring's positions, longitude then latitude; a z is not read.
pub(crate) struct WkbPositions<'a> {
    le: bool,
    step: usize,
    bytes: &'a [u8],
}

impl Iterator for WkbPositions<'_> {
    type Item = geo3d::Geodetic;

    #[inline]
    fn next(&mut self) -> Option<geo3d::Geodetic> {
        if self.bytes.len() < self.step {
            return None;
        }
        let p = geo3d::Geodetic::from_lon_lat(f64_at(self.bytes, 0, self.le), f64_at(self.bytes, 8, self.le), 0.0);
        self.bytes = &self.bytes[self.step..];
        Some(p)
    }
}

/// A geometry as GeoJSON, with z where it has one (an m is not a coordinate). `None` for an empty
/// point, which GeoJSON has no form for.
fn geojson_of(g: &impl GeometryTrait<T = f64>) -> Option<serde_json::Value> {
    use serde_json::{json, Value as J};
    fn position(c: &impl CoordTrait<T = f64>) -> Option<J> {
        let n = match c.dim() {
            Dimensions::Xy | Dimensions::Xym => 2,
            Dimensions::Xyz | Dimensions::Xyzm => 3,
            Dimensions::Unknown(_) => return None,
        };
        Some((0..n).map(|k| c.nth_or_panic(k)).collect())
    }
    fn line(l: &impl LineStringTrait<T = f64>) -> Option<J> {
        l.coords().map(|c| position(&c)).collect()
    }
    fn rings(p: &impl PolygonTrait<T = f64>) -> Option<J> {
        p.exterior()
            .into_iter()
            .chain(p.interiors())
            .map(|r| line(&r))
            .collect()
    }
    let (kind, coordinates) = match g.as_type() {
        GeometryType::Point(p) => ("Point", position(&p.coord()?)?),
        GeometryType::LineString(l) => ("LineString", line(l)?),
        GeometryType::Polygon(p) => ("Polygon", rings(p)?),
        GeometryType::MultiPoint(m) => (
            "MultiPoint",
            m.points().map(|p| position(&p.coord()?)).collect::<Option<J>>()?,
        ),
        GeometryType::MultiLineString(m) => (
            "MultiLineString",
            m.line_strings().map(|l| line(&l)).collect::<Option<J>>()?,
        ),
        GeometryType::MultiPolygon(m) => ("MultiPolygon", m.polygons().map(|p| rings(&p)).collect::<Option<J>>()?),
        GeometryType::GeometryCollection(c) => {
            let geometries: Option<J> = c.geometries().map(|g| geojson_of(&g)).collect();
            return Some(json!({"type": "GeometryCollection", "geometries": geometries?}));
        }
        // a rect, a triangle or a line: not WKB geometries
        _ => return None,
    };
    Some(json!({"type": kind, "coordinates": coordinates}))
}

/// [`cell_to_value`] for an array whose type [`has_value_form`] — checked once per column, so
/// reading each cell carries no error path.
pub(crate) fn value_at(array: &ArrayRef, i: usize) -> Value {
    if array.is_null(i) {
        return Value::Null;
    }
    match array.data_type() {
        DataType::Null => Value::Null,
        DataType::Boolean => Value::Bool(array.as_boolean().value(i)),
        DataType::Float64 => Value::Num(array.as_primitive::<Float64Type>().value(i)),
        DataType::Float32 => Value::Num(f64::from(array.as_primitive::<Float32Type>().value(i))),
        DataType::Float16 => Value::Num(f64::from(array.as_primitive::<Float16Type>().value(i))),
        DataType::Int64 => Value::Num(array.as_primitive::<Int64Type>().value(i) as f64),
        DataType::Int32 => Value::Num(f64::from(array.as_primitive::<Int32Type>().value(i))),
        DataType::Int16 => Value::Num(f64::from(array.as_primitive::<Int16Type>().value(i))),
        DataType::Int8 => Value::Num(f64::from(array.as_primitive::<Int8Type>().value(i))),
        DataType::UInt64 => Value::Num(array.as_primitive::<UInt64Type>().value(i) as f64),
        DataType::UInt32 => Value::Num(f64::from(array.as_primitive::<UInt32Type>().value(i))),
        DataType::UInt16 => Value::Num(f64::from(array.as_primitive::<UInt16Type>().value(i))),
        DataType::UInt8 => Value::Num(f64::from(array.as_primitive::<UInt8Type>().value(i))),
        DataType::Utf8 => Value::Str(array.as_string::<i32>().value(i).to_string()),
        DataType::LargeUtf8 => Value::Str(array.as_string::<i64>().value(i).to_string()),
        DataType::Utf8View => Value::Str(array.as_string_view().value(i).to_string()),
        DataType::Dictionary(_, _) => {
            let dict = array.as_any_dictionary();
            value_at(dict.values(), dict.normalized_keys()[i])
        }
        DataType::List(_) => list(&array.as_list::<i32>().value(i)),
        DataType::LargeList(_) => list(&array.as_list::<i64>().value(i)),
        DataType::FixedSizeList(_, _) => list(&array.as_fixed_size_list().value(i)),
        DataType::Struct(fields) => {
            let s = array.as_struct();
            Value::Obj(
                fields
                    .iter()
                    .zip(s.columns())
                    .map(|(f, c)| (f.name().clone(), value_at(c, i)))
                    .collect(),
            )
        }
        // unreachable once the type is checked: `has_value_form` admits exactly the arms above
        _ => Value::Null,
    }
}

fn list(items: &ArrayRef) -> Value {
    Value::List((0..items.len()).map(|j| value_at(items, j)).collect())
}

/// The Arrow type a dialect result kind is materialised as.
pub fn data_type_for(kind: Kind) -> DataType {
    match kind {
        Kind::Num => DataType::Float64,
        Kind::Str => DataType::Utf8,
        Kind::Bool => DataType::Boolean,
        Kind::Null => DataType::Null,
    }
}

/// The static kind of a dialect expression's result, when it can be known before evaluation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
    /// A number (`Float64`).
    Num,
    /// A string (`Utf8`).
    Str,
    /// A boolean.
    Bool,
    /// Always null.
    Null,
}

impl Kind {
    /// The kind a column of this Arrow type reads as, or `None` if the translator does not handle
    /// it (lists, structs, temporal types, …).
    pub fn of_data_type(t: &DataType) -> Option<Kind> {
        match t {
            DataType::Null => Some(Kind::Null),
            DataType::Boolean => Some(Kind::Bool),
            DataType::Int8
            | DataType::Int16
            | DataType::Int32
            | DataType::Int64
            | DataType::UInt8
            | DataType::UInt16
            | DataType::UInt32
            | DataType::UInt64
            | DataType::Float32
            | DataType::Float64 => Some(Kind::Num),
            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Some(Kind::Str),
            DataType::Dictionary(_, values) => Kind::of_data_type(values),
            _ => None,
        }
    }
}

/// Materialise per-row results as an Arrow array of `data_type`. A value of the wrong kind for the
/// declared type is an execution error (the dialect returned something the plan did not declare).
pub fn values_to_array(values: &[Value], data_type: &DataType) -> Result<ArrayRef> {
    let wrong = |v: &Value| {
        DataFusionError::Execution(format!(
            "fv-value: expression produced a {} where the plan declared {data_type}",
            v.type_name()
        ))
    };
    Ok(match data_type {
        DataType::Float64 => Arc::new(
            values
                .iter()
                .map(|v| match v {
                    Value::Null => Ok(None),
                    Value::Num(n) => Ok(Some(*n)),
                    other => Err(wrong(other)),
                })
                .collect::<Result<Float64Array>>()?,
        ),
        DataType::Utf8 => Arc::new(
            values
                .iter()
                .map(|v| match v {
                    Value::Null => Ok(None),
                    Value::Str(s) => Ok(Some(s.clone())),
                    other => Err(wrong(other)),
                })
                .collect::<Result<StringArray>>()?,
        ),
        DataType::Boolean => Arc::new(
            values
                .iter()
                .map(|v| match v {
                    Value::Null => Ok(None),
                    Value::Bool(b) => Ok(Some(*b)),
                    other => Err(wrong(other)),
                })
                .collect::<Result<BooleanArray>>()?,
        ),
        DataType::Null => Arc::new(NullArray::new(values.len())),
        other => {
            return Err(DataFusionError::NotImplemented(format!(
                "fv-value: cannot materialise dialect values as {other}"
            )))
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::arrow::array::{Int32Array, ListBuilder, StringViewArray};

    #[test]
    fn cells_convert_by_type() {
        let ints: ArrayRef = Arc::new(Int32Array::from(vec![Some(7), None]));
        assert_eq!(cell_to_value(&ints, 0).unwrap(), Value::Num(7.0));
        assert_eq!(cell_to_value(&ints, 1).unwrap(), Value::Null);
        let views: ArrayRef = Arc::new(StringViewArray::from(vec!["x"]));
        assert_eq!(cell_to_value(&views, 0).unwrap(), Value::from("x"));
        let mut lb = ListBuilder::new(Float64Array::builder(2));
        lb.values().append_value(1.0);
        lb.values().append_value(2.0);
        lb.append(true);
        let list: ArrayRef = Arc::new(lb.finish());
        assert_eq!(cell_to_value(&list, 0).unwrap(), Value::from(vec![1.0, 2.0]));
    }

    #[test]
    fn cells_check_the_type_once_and_refuse_one_with_no_dialect_value() {
        use datafusion::arrow::array::BinaryArray;
        let words: ArrayRef = Arc::new(StringViewArray::from(vec!["a", "b"]));
        let cells = Cells::of(&words).unwrap();
        assert_eq!((cells.value(0), cells.value(1)), (Value::from("a"), Value::from("b")));
        let bytes: ArrayRef = Arc::new(BinaryArray::from(vec![b"x".as_ref()]));
        let err = Cells::of(&bytes).unwrap_err().to_string();
        assert!(
            err.contains("Binary") && err.contains("no form in the dialect"),
            "{err}"
        );
        assert!(cell_to_value(&bytes, 0).is_err());
        assert!(!has_value_form(&DataType::Date32) && has_value_form(&DataType::Float16));
    }

    #[test]
    fn kinds_and_materialisation() {
        assert_eq!(Kind::of_data_type(&DataType::Int64), Some(Kind::Num));
        assert_eq!(Kind::of_data_type(&DataType::Utf8View), Some(Kind::Str));
        assert_eq!(Kind::of_data_type(&DataType::Date32), None);
        let a = values_to_array(&[Value::Num(1.5), Value::Null], &DataType::Float64).unwrap();
        assert_eq!(a.len(), 2);
        assert!(a.is_null(1));
        assert!(values_to_array(&[Value::from("s")], &DataType::Float64).is_err());
        assert_eq!(data_type_for(Kind::Bool), DataType::Boolean);
    }
}