perspective-python 5.7.0

Interactive data grid, pivot table and charts for large, real-time and streaming datasets, with a Jupyter widget and WebSocket server.
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
#  ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
#  ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
#  ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
#  ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
#  ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
#  ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
#  ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
#  ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
#  ┃ This file is part of the Perspective library, distributed under the terms ┃
#  ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
#  ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

import json
from decimal import Decimal

import pyarrow as pa
import pytest
import perspective as psp


client = psp.Server().new_local_client()
Table = client.table


def arrow_bytes(table):
    sink = pa.BufferOutputStream()
    with pa.RecordBatchFileWriter(sink, table.schema) as writer:
        writer.write_table(table)

    return sink.getvalue().to_pybytes()


class TestTableArrowStruct(object):
    def test_struct_flattens_to_dotted_columns(self):
        data = pa.table(
            {
                "id": pa.array([1, 2], type=pa.int64()),
                "s": pa.array(
                    [{"a": 10, "b": 1.5}, {"a": 20, "b": 2.5}],
                    type=pa.struct([("a", pa.int64()), ("b", pa.float64())]),
                ),
            }
        )

        tbl = Table(data)
        assert tbl.schema() == {
            "id": "integer",
            "s.a": "integer",
            "s.b": "float",
        }

        assert tbl.view().to_columns() == {
            "id": [1, 2],
            "s.a": [10, 20],
            "s.b": [1.5, 2.5],
        }

    def test_struct_of_struct_recurses(self):
        inner = pa.struct([("c", pa.int64())])
        data = pa.table(
            {
                "s": pa.array(
                    [{"b": {"c": 1}}, {"b": {"c": 2}}],
                    type=pa.struct([("b", inner)]),
                )
            }
        )

        tbl = Table(data)
        assert tbl.schema() == {"s.b.c": "integer"}
        assert tbl.view().to_columns() == {"s.b.c": [1, 2]}

    def test_struct_null_parent_nulls_all_leaves(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"a": 1, "b": 2}, None, {"a": 3, "b": 4}],
                    type=pa.struct([("a", pa.int64()), ("b", pa.int64())]),
                )
            }
        )

        tbl = Table(data)
        assert tbl.view().to_columns() == {
            "s.a": [1, None, 3],
            "s.b": [2, None, 4],
        }

    def test_struct_null_child_and_null_parent(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"a": 1}, {"a": None}, None],
                    type=pa.struct([("a", pa.int64())]),
                )
            }
        )

        tbl = Table(data)
        assert tbl.view().to_columns() == {"s.a": [1, None, None]}

    def test_struct_sliced_input(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"a": 1}, {"a": 2}, {"a": 3}, {"a": 4}],
                    type=pa.struct([("a", pa.int64())]),
                )
            }
        ).slice(1, 2)

        tbl = Table(data)
        assert tbl.view().to_columns() == {"s.a": [2, 3]}

    def test_struct_multi_chunk(self):
        chunk = pa.array([{"a": 1}], type=pa.struct([("a", pa.int64())]))
        data = pa.table({"s": pa.chunked_array([chunk, chunk, chunk])})
        tbl = Table(data)
        assert tbl.view().to_columns() == {"s.a": [1, 1, 1]}

    def test_struct_update_matches_declared_dotted_schema(self):
        tbl = Table({"id": "integer", "s.a": "integer"})
        tbl.update(
            arrow_bytes(
                pa.table(
                    {
                        "id": pa.array([1], type=pa.int64()),
                        "s": pa.array(
                            [{"a": 7}], type=pa.struct([("a", pa.int64())])
                        ),
                    }
                )
            )
        )

        assert tbl.view().to_columns() == {"id": [1], "s.a": [7]}


class TestTableArrowList(object):
    def test_list_zip_is_the_default(self):
        data = pa.table(
            {
                "x": pa.array([1, 2], type=pa.int64()),
                "y": pa.array([[10, 20, 30], [40]], type=pa.list_(pa.int64())),
            }
        )

        tbl = Table(data)
        assert tbl.schema() == {"x": "integer", "y": "integer"}
        assert tbl.view().to_columns() == {
            "x": [1, 1, 1, 2],
            "y": [10, 20, 30, 40],
        }

    def test_list_empty_yields_one_null_row(self):
        data = pa.table(
            {
                "x": pa.array([1, 2], type=pa.int64()),
                "y": pa.array([[], [40]], type=pa.list_(pa.int64())),
            }
        )

        assert Table(data).view().to_columns() == {
            "x": [1, 2],
            "y": [None, 40],
        }

    def test_list_null_yields_one_null_row(self):
        data = pa.table(
            {
                "x": pa.array([1, 2], type=pa.int64()),
                "y": pa.array([None, [40]], type=pa.list_(pa.int64())),
            }
        )

        assert Table(data).view().to_columns() == {
            "x": [1, 2],
            "y": [None, 40],
        }

    def test_list_of_struct_composes_both_passes(self):
        data = pa.table(
            {
                "id": pa.array([1], type=pa.int64()),
                "orders": pa.array(
                    [[{"price": 1.5}, {"price": 2.5}]],
                    type=pa.list_(pa.struct([("price", pa.float64())])),
                ),
            }
        )

        tbl = Table(data)
        assert tbl.schema() == {"id": "integer", "orders.price": "float"}
        assert tbl.view().to_columns() == {
            "id": [1, 1],
            "orders.price": [1.5, 2.5],
        }

    def test_list_nested_inside_a_struct(self):
        data = pa.table(
            {
                "id": pa.array([1, 2], type=pa.int64()),
                "s": pa.array(
                    [{"a": [10, 20]}, {"a": [30]}],
                    type=pa.struct([("a", pa.list_(pa.int64()))]),
                ),
            }
        )

        tbl = Table(data)
        assert tbl.schema() == {"id": "integer", "s.a": "integer"}
        assert tbl.view().to_columns() == {
            "id": [1, 1, 2],
            "s.a": [10, 20, 30],
        }

    def test_nested_list_recurses(self):
        data = pa.table(
            {
                "y": pa.array(
                    [[[1, 2], [3]]], type=pa.list_(pa.list_(pa.int64()))
                )
            }
        )

        assert Table(data).view().to_columns() == {"y": [1, 2, 3]}

    def test_list_zip_equal_lengths(self):
        data = pa.table(
            {
                "a": pa.array([[1, 2]], type=pa.list_(pa.int64())),
                "b": pa.array([[3, 4]], type=pa.list_(pa.int64())),
            }
        )

        assert Table(data).view().to_columns() == {"a": [1, 2], "b": [3, 4]}

    def test_list_multi_chunk(self):
        chunk = pa.array([[1, 2]], type=pa.list_(pa.int64()))
        data = pa.table({"y": pa.chunked_array([chunk, chunk])})
        assert Table(data).view().to_columns() == {"y": [1, 2, 1, 2]}

    def test_list_cartesian(self):
        data = pa.table(
            {
                "a": pa.array([[1, 2]], type=pa.list_(pa.int64())),
                "b": pa.array([[3, 4, 5]], type=pa.list_(pa.int64())),
            }
        )

        tbl = Table(data, list_flatten="cartesian")
        assert tbl.view().to_columns() == {
            "a": [1, 1, 1, 2, 2, 2],
            "b": [3, 4, 5, 3, 4, 5],
        }

    def test_list_cartesian_empty_counts_as_one(self):
        data = pa.table(
            {
                "a": pa.array([[1, 2]], type=pa.list_(pa.int64())),
                "b": pa.array([[]], type=pa.list_(pa.int64())),
            }
        )

        tbl = Table(data, list_flatten="cartesian")
        assert tbl.view().to_columns() == {"a": [1, 2], "b": [None, None]}

    def test_list_stringify_preserves_legacy_behavior(self):
        data = pa.table(
            {
                "x": pa.array([1, 2], type=pa.int64()),
                "y": pa.array([[10, 20], [30]], type=pa.list_(pa.int64())),
            }
        )

        tbl = Table(data, list_flatten="stringify")
        assert tbl.schema() == {"x": "integer", "y": "string"}
        assert tbl.view().to_columns() == {
            "x": [1, 2],
            "y": ["[10,20]", "[30]"],
        }

    def test_list_stringify_integer_widths(self):
        data = pa.table(
            {
                "i8": pa.array([[-1, 2]], type=pa.list_(pa.int8())),
                "i16": pa.array([[-300, 300]], type=pa.list_(pa.int16())),
                "i32": pa.array([[-70000, 70000]], type=pa.list_(pa.int32())),
                "i64": pa.array(
                    [[-(2**40), 2**40]], type=pa.list_(pa.int64())
                ),
                "u8": pa.array([[255]], type=pa.list_(pa.uint8())),
                "u16": pa.array([[65535]], type=pa.list_(pa.uint16())),
                "u32": pa.array([[4294967295]], type=pa.list_(pa.uint32())),
                # Above INT64_MAX, so a signed writer would emit a negative.
                "u64": pa.array(
                    [[18446744073709551615]], type=pa.list_(pa.uint64())
                ),
            }
        )

        assert Table(data, list_flatten="stringify").view().to_columns() == {
            "i8": ["[-1,2]"],
            "i16": ["[-300,300]"],
            "i32": ["[-70000,70000]"],
            "i64": ["[-1099511627776,1099511627776]"],
            "u8": ["[255]"],
            "u16": ["[65535]"],
            "u32": ["[4294967295]"],
            "u64": ["[18446744073709551615]"],
        }

    def test_list_flatten_mode_persists_across_update(self):
        schema = pa.schema(
            [("x", pa.int64()), ("y", pa.list_(pa.int64()))]
        )

        tbl = Table(
            arrow_bytes(pa.table({"x": [1], "y": [[10, 20]]}, schema=schema)),
            list_flatten="cartesian",
        )

        tbl.update(
            arrow_bytes(pa.table({"x": [2], "y": [[30, 40]]}, schema=schema))
        )

        assert tbl.view().to_columns() == {
            "x": [1, 1, 2, 2],
            "y": [10, 20, 30, 40],
        }

    def test_list_limit_counts_expanded_rows(self):
        data = pa.table(
            {"y": pa.array([[1, 2, 3, 4]], type=pa.list_(pa.int64()))}
        )

        assert Table(data, limit=2).view().to_columns() == {"y": [3, 4]}


class TestTableArrowExpandedIndex(object):
    """An index is only rejected when expansion would REPEAT it. A column drawn
    from the exploded list takes a distinct element per row, so it is a
    legitimate key."""

    def orders(self, ids, prices):
        return pa.table(
            {
                "batch": pa.array([1], type=pa.int64()),
                "orders": pa.array(
                    [[{"id": i, "price": p} for i, p in zip(ids, prices)]],
                    type=pa.list_(
                        pa.struct([("id", pa.int64()), ("price", pa.float64())])
                    ),
                ),
            }
        )

    def test_index_on_a_column_from_the_list_is_allowed(self):
        tbl = Table(self.orders([1, 2, 3], [1.5, 2.5, 3.5]), index="orders.id")
        assert tbl.view().to_columns() == {
            "batch": [1, 1, 1],
            "orders.id": [1, 2, 3],
            "orders.price": [1.5, 2.5, 3.5],
        }

    def test_index_from_the_list_updates_by_element(self):
        tbl = Table(self.orders([1, 2], [1.5, 2.5]), index="orders.id")
        tbl.update(arrow_bytes(self.orders([2, 3], [9.5, 3.5])))
        assert tbl.view().to_columns() == {
            "batch": [1, 1, 1],
            "orders.id": [1, 2, 3],
            "orders.price": [1.5, 9.5, 3.5],
        }

    def test_index_on_a_sibling_is_rejected(self):
        with pytest.raises(psp.PerspectiveError, match=r"`batch`"):
            Table(self.orders([1, 2], [1.5, 2.5]), index="batch")

    def test_index_on_a_sibling_is_rejected_from_a_zero_row_arrow(self):
        with pytest.raises(psp.PerspectiveError, match=r"`batch`"):
            Table(self.orders([], []).slice(0, 0), index="batch")

    def test_index_from_the_list_is_accepted_from_a_zero_row_arrow(self):
        tbl = Table(self.orders([], []).slice(0, 0), index="orders.id")
        assert tbl.size() == 0
        tbl.update(arrow_bytes(self.orders([1, 2], [1.5, 2.5])))
        assert tbl.view().to_columns() == {
            "batch": [1, 1],
            "orders.id": [1, 2],
            "orders.price": [1.5, 2.5],
        }

    def test_index_on_a_list_column_itself_is_allowed(self):
        data = pa.table(
            {
                "x": pa.array([1], type=pa.int64()),
                "id": pa.array([[10, 20]], type=pa.list_(pa.int64())),
            }
        )

        assert Table(data, index="id").view().to_columns() == {
            "x": [1, 1],
            "id": [10, 20],
        }

    def test_cartesian_with_two_lists_repeats_every_column(self):
        data = pa.table(
            {
                "id": pa.array([[1, 2]], type=pa.list_(pa.int64())),
                "b": pa.array([[3, 4, 5]], type=pa.list_(pa.int64())),
            }
        )

        with pytest.raises(psp.PerspectiveError, match=r"`id`"):
            Table(data, index="id", list_flatten="cartesian")

    def test_cartesian_with_one_list_is_allowed(self):
        data = pa.table(
            {
                "x": pa.array([1], type=pa.int64()),
                "id": pa.array([[10, 20]], type=pa.list_(pa.int64())),
            }
        )

        tbl = Table(data, index="id", list_flatten="cartesian")
        assert tbl.view().to_columns() == {"x": [1, 1], "id": [10, 20]}

    def test_stringify_keeps_a_sibling_index_usable(self):
        data = pa.table(
            {
                "id": pa.array([1, 2], type=pa.int64()),
                "y": pa.array([[10, 20], [30]], type=pa.list_(pa.int64())),
            }
        )

        tbl = Table(data, index="id", list_flatten="stringify")
        assert tbl.view().to_columns() == {
            "id": [1, 2],
            "y": ["[10,20]", "[30]"],
        }


class TestTableArrowSchemaListFlatten(object):
    def test_schema_table_stringify_keeps_a_sibling_index_usable(self):
        tbl = Table(
            {"id": "integer", "y": "string"},
            index="id",
            list_flatten="stringify",
        )

        tbl.update(
            arrow_bytes(
                pa.table(
                    {
                        "id": pa.array([1, 2], type=pa.int64()),
                        "y": pa.array(
                            [[10, 20], [30]], type=pa.list_(pa.int64())
                        ),
                    }
                )
            )
        )

        assert tbl.view().to_columns() == {
            "id": [1, 2],
            "y": ["[10,20]", "[30]"],
        }

    def test_schema_table_cartesian_persists_across_update(self):
        tbl = Table(
            {"a": "integer", "b": "integer"}, list_flatten="cartesian"
        )

        tbl.update(
            arrow_bytes(
                pa.table(
                    {
                        "a": pa.array([[1, 2]], type=pa.list_(pa.int64())),
                        "b": pa.array([[3, 4, 5]], type=pa.list_(pa.int64())),
                    }
                )
            )
        )

        assert tbl.view().to_columns() == {
            "a": [1, 1, 1, 2, 2, 2],
            "b": [3, 4, 5, 3, 4, 5],
        }


class TestTableArrowGather(object):
    """The expansion is deferred into the `t_column` write rather than
    materialized in Arrow, so these stress the gather paths specifically."""

    def test_expansion_gathers_across_chunks(self):
        x = pa.chunked_array(
            [pa.array([1], type=pa.int64()), pa.array([2], type=pa.int64())]
        )

        y = pa.chunked_array(
            [
                pa.array([[10, 20]], type=pa.list_(pa.int64())),
                pa.array([[30]], type=pa.list_(pa.int64())),
            ]
        )

        assert Table(pa.table({"x": x, "y": y})).view().to_columns() == {
            "x": [1, 1, 2],
            "y": [10, 20, 30],
        }

    def test_expansion_gathers_strings(self):
        data = pa.table(
            {
                "s": pa.array(["a", "b"], type=pa.string()),
                "y": pa.array([[1, 2, 3], [4]], type=pa.list_(pa.int64())),
            }
        )

        assert Table(data).view().to_columns() == {
            "s": ["a", "a", "a", "b"],
            "y": [1, 2, 3, 4],
        }

    def test_expansion_gathers_nulls_in_siblings(self):
        data = pa.table(
            {
                "x": pa.array([None, 2], type=pa.int64()),
                "y": pa.array([[10, 20], [30]], type=pa.list_(pa.int64())),
            }
        )

        assert Table(data).view().to_columns() == {
            "x": [None, None, 2],
            "y": [10, 20, 30],
        }

    def test_expansion_of_all_empty_lists(self):
        data = pa.table(
            {
                "x": pa.array([1, 2], type=pa.int64()),
                "y": pa.array([[], []], type=pa.list_(pa.int64())),
            }
        )

        assert Table(data).view().to_columns() == {
            "x": [1, 2],
            "y": [None, None],
        }

    def test_sliced_input_with_nulls(self):
        data = pa.table(
            {"a": pa.array([1, None, 3, None, 5], type=pa.int64())}
        ).slice(1, 3)

        assert Table(data).view().to_columns() == {"a": [None, 3, None]}


class TestTableArrowFlatUnaffected(object):
    """A table with neither struct nor list columns must be untouched by
    normalization; these lock the flat path against regressions."""

    def test_flat_arrow_roundtrip(self):
        data = pa.table(
            {
                "a": pa.array([1, 2, 3], type=pa.int64()),
                "b": pa.array(["x", "y", "z"], type=pa.string()),
                "c": pa.array([1.5, 2.5, 3.5], type=pa.float64()),
            }
        )

        tbl = Table(data)
        assert tbl.schema() == {"a": "integer", "b": "string", "c": "float"}
        assert tbl.view().to_columns() == {
            "a": [1, 2, 3],
            "b": ["x", "y", "z"],
            "c": [1.5, 2.5, 3.5],
        }

    def test_flat_arrow_indexed_update(self):
        data = pa.table(
            {
                "a": pa.array([1, 2], type=pa.int64()),
                "b": pa.array([10, 20], type=pa.int64()),
            }
        )

        tbl = Table(data, index="a")
        tbl.update(
            arrow_bytes(
                pa.table(
                    {
                        "a": pa.array([2], type=pa.int64()),
                        "b": pa.array([99], type=pa.int64()),
                    }
                )
            )
        )

        assert tbl.view().to_columns() == {"a": [1, 2], "b": [10, 99]}


class TestTableArrowMap(object):
    map_type = pa.map_(pa.string(), pa.int64())

    def test_map_pivots_to_dotted_columns(self):
        data = pa.table(
            {
                "id": pa.array([1, 2], type=pa.int64()),
                "m": pa.array([[("a", 1), ("b", 2)], [("b", 3)]], type=self.map_type),
            }
        )

        tbl = Table(data)
        assert tbl.schema() == {
            "id": "integer",
            "m.a": "integer",
            "m.b": "integer",
        }

        assert tbl.view().to_columns() == {
            "id": [1, 2],
            "m.a": [1, None],
            "m.b": [2, 3],
        }

    def test_empty_and_null_maps_yield_nulls(self):
        data = pa.table(
            {"m": pa.array([[("a", 1)], [], None], type=self.map_type)}
        )

        assert Table(data).view().to_columns() == {"m.a": [1, None, None]}

    def test_null_item_is_a_null_cell(self):
        data = pa.table(
            {"m": pa.array([[("a", None)], [("a", 2)]], type=self.map_type)}
        )

        assert Table(data).view().to_columns() == {"m.a": [None, 2]}

    def test_duplicate_key_in_a_row_last_wins(self):
        data = pa.table(
            {"m": pa.array([[("a", 1), ("a", 2)]], type=self.map_type)}
        )

        assert Table(data).view().to_columns() == {"m.a": [2]}

    def test_map_of_struct_pivots_both(self):
        item = pa.struct([("a", pa.int64()), ("b", pa.float64())])
        data = pa.table(
            {
                "m": pa.array(
                    [[("x", {"a": 1, "b": 1.5})]],
                    type=pa.map_(pa.string(), item),
                )
            }
        )

        assert Table(data).view().to_columns() == {"m.x.a": [1], "m.x.b": [1.5]}

    def test_map_of_list_follows_list_flatten(self):
        data = pa.table(
            {
                "id": pa.array([1], type=pa.int64()),
                "m": pa.array(
                    [[("x", [1, 2])]],
                    type=pa.map_(pa.string(), pa.list_(pa.int64())),
                ),
            }
        )

        assert Table(data).view().to_columns() == {"id": [1, 1], "m.x": [1, 2]}
        assert Table(data, list_flatten="stringify").view().to_columns() == {
            "id": [1],
            "m.x": ["[1,2]"],
        }

    def test_map_of_lists_zips_as_siblings(self):
        item = pa.list_(pa.int64())
        data = pa.table(
            {
                "m": pa.array(
                    [[("x", [1, 2]), ("y", [3, 4])], [("x", [5])]],
                    type=pa.map_(pa.string(), item),
                )
            }
        )

        assert Table(data).view().to_columns() == {
            "m.x": [1, 2, 5],
            "m.y": [3, 4, None],
        }

        ragged = pa.table(
            {
                "m": pa.array(
                    [[("x", [1, 2]), ("y", [3])]],
                    type=pa.map_(pa.string(), item),
                )
            }
        )

        with pytest.raises(psp.PerspectiveError, match=r"`m\.x`"):
            Table(ragged)

        assert Table(ragged, list_flatten="cartesian").view().to_columns() == {
            "m.x": [1, 2],
            "m.y": [3, 3],
        }

    def test_map_of_map_pivots_twice(self):
        data = pa.table(
            {
                "m": pa.array(
                    [[("x", [("y", 1)])]],
                    type=pa.map_(pa.string(), self.map_type),
                )
            }
        )

        assert Table(data).view().to_columns() == {"m.x.y": [1]}

    def test_map_under_struct(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"m": [("a", 1)]}],
                    type=pa.struct([("m", self.map_type)]),
                )
            }
        )

        assert Table(data).view().to_columns() == {"s.m.a": [1]}

    def test_list_of_maps_explodes_then_pivots(self):
        data = pa.table(
            {
                "id": pa.array([1], type=pa.int64()),
                "m": pa.array(
                    [[[("a", 1)], [("b", 2)]]], type=pa.list_(self.map_type)
                ),
            }
        )

        assert Table(data).view().to_columns() == {
            "id": [1, 1],
            "m.a": [1, None],
            "m.b": [None, 2],
        }

    def test_multi_chunk_unions_keys(self):
        data = pa.concat_tables(
            [
                pa.table({"m": pa.array([[("a", 1)]], type=self.map_type)}),
                pa.table({"m": pa.array([[("b", 2)]], type=self.map_type)}),
            ]
        )

        assert data.column("m").num_chunks == 2
        assert Table(data).view().to_columns() == {
            "m.a": [1, None],
            "m.b": [None, 2],
        }

    def test_sliced_input(self):
        data = pa.table(
            {"m": pa.array([[("a", 1)], [("b", 2)], None], type=self.map_type)}
        ).slice(1)

        assert Table(data).view().to_columns() == {"m.b": [2, None]}

    def test_dictionary_keys_pivot_like_strings(self):
        keys = pa.array(["a", "b", "a"]).dictionary_encode()
        items = pa.array([1, 2, 3], type=pa.int64())
        data = pa.table({"m": pa.MapArray.from_arrays([0, 2, 3], keys, items)})
        assert Table(data).view().to_columns() == {
            "m.a": [1, 3],
            "m.b": [2, None],
        }

    def test_non_string_keys_are_rejected(self):
        data = pa.table(
            {"m": pa.array([[(1, "x")]], type=pa.map_(pa.int32(), pa.string()))}
        )

        with pytest.raises(psp.PerspectiveError, match=r"`m`"):
            Table(data)

    def test_schema_table_update_matches_keys(self):
        tbl = Table(
            {"id": "integer", "m.a": "integer", "m.b": "integer"}, index="id"
        )

        def batch(entries):
            return arrow_bytes(
                pa.table(
                    {
                        "id": pa.array([1], type=pa.int64()),
                        "m": pa.array([entries], type=self.map_type),
                    }
                )
            )

        tbl.update(batch([("a", 1), ("b", 2)]))
        tbl.update(batch([("a", 10)]))
        assert tbl.view().to_columns() == {"id": [1], "m.a": [10], "m.b": [2]}
        tbl.update(batch([("c", 5)]))
        assert tbl.view().to_columns() == {"id": [1], "m.a": [10], "m.b": [2]}

    def test_columns_follow_first_appearance(self):
        data = pa.table(
            {"m": pa.array([[("b", 1), ("a", 2)], [("c", 3)]], type=self.map_type)}
        )

        assert Table(data).columns() == ["m.b", "m.a", "m.c"]

    def test_key_colliding_with_a_literal_column_is_rejected(self):
        data = pa.table(
            {
                "m.a": pa.array([1], type=pa.int64()),
                "m": pa.array([[("a", 2)]], type=self.map_type),
            }
        )

        with pytest.raises(psp.PerspectiveError, match=r"`m\.a`"):
            Table(data)

    def test_index_on_a_pivoted_key(self):
        data = pa.table(
            {
                "m": pa.array(
                    [[("id", 1), ("v", 10)], [("id", 2), ("v", 20)]],
                    type=self.map_type,
                )
            }
        )

        tbl = Table(data, index="m.id")
        tbl.update(
            arrow_bytes(
                pa.table(
                    {"m": pa.array([[("id", 2), ("v", 99)]], type=self.map_type)}
                )
            )
        )

        assert tbl.view().to_columns() == {"m.id": [1, 2], "m.v": [10, 99]}


class TestTableArrowStructStringify(object):
    def test_struct_is_json_text(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"a": 1, "b": "x"}, None, {"a": None, "b": "y"}],
                    type=pa.struct([("a", pa.int64()), ("b", pa.string())]),
                )
            }
        )

        tbl = Table(data, struct_flatten="stringify")
        assert tbl.schema() == {"s": "string"}
        assert tbl.view().to_columns() == {
            "s": ['{"a":1,"b":"x"}', None, '{"a":null,"b":"y"}']
        }

    def test_map_is_json_text(self):
        data = pa.table(
            {
                "m": pa.array(
                    [[("a", 1), ("b", 2)], [], None],
                    type=pa.map_(pa.string(), pa.int64()),
                )
            }
        )

        assert Table(data, struct_flatten="stringify").view().to_columns() == {
            "m": ['{"a":1,"b":2}', "{}", None]
        }

    def test_map_keys_are_coerced_to_text(self):
        data = pa.table(
            {"m": pa.array([[(1, "x")]], type=pa.map_(pa.int32(), pa.string()))}
        )

        assert Table(data, struct_flatten="stringify").view().to_columns() == {
            "m": ['{"1":"x"}']
        }

    def test_outer_struct_wins_over_list_flatten(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"a": 1, "tags": ["x", "y"]}],
                    type=pa.struct(
                        [("a", pa.int64()), ("tags", pa.list_(pa.string()))]
                    ),
                )
            }
        )

        assert Table(data, struct_flatten="stringify").view().to_columns() == {
            "s": ['{"a":1,"tags":["x","y"]}']
        }

    def test_list_of_struct_explodes_then_stringifies(self):
        data = pa.table(
            {
                "id": pa.array([1], type=pa.int64()),
                "l": pa.array(
                    [[{"a": 1}, {"a": 2}]],
                    type=pa.list_(pa.struct([("a", pa.int64())])),
                ),
            }
        )

        assert Table(data, struct_flatten="stringify").view().to_columns() == {
            "id": [1, 1],
            "l": ['{"a":1}', '{"a":2}'],
        }

        tbl = Table(data, struct_flatten="stringify", list_flatten="stringify")
        assert tbl.view().to_columns() == {"id": [1], "l": ['[{"a":1},{"a":2}]']}

    def test_json_object_is_json_text(self):
        tbl = Table([{"s": {"a": 1, "b": "x"}}], struct_flatten="stringify")
        assert tbl.schema() == {"s": "string"}
        assert tbl.view().to_columns() == {"s": ['{"a":1,"b":"x"}']}

    def test_mode_persists_across_update_on_a_schema_table(self):
        tbl = Table({"s": "string"}, struct_flatten="stringify")
        tbl.update(
            arrow_bytes(
                pa.table(
                    {
                        "s": pa.array(
                            [{"a": 1}], type=pa.struct([("a", pa.int64())])
                        )
                    }
                )
            )
        )

        tbl.update([{"s": {"a": 2}}])
        assert tbl.view().to_columns() == {"s": ['{"a":1}', '{"a":2}']}

    def test_default_pivots(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"a": 1}], type=pa.struct([("a", pa.int64())])
                )
            }
        )

        assert Table(data, struct_flatten="pivot").view().to_columns() == {
            "s.a": [1]
        }


class TestTableArrowMapFlatten(object):
    map_type = pa.map_(pa.string(), pa.int64())

    def mixed(self):
        return pa.table(
            {
                "s": pa.array([{"a": 1}], type=pa.struct([("a", pa.int64())])),
                "m": pa.array([[("a", 1), ("b", 2)]], type=self.map_type),
            }
        )

    def test_map_stringifies_while_struct_pivots(self):
        tbl = Table(self.mixed(), map_flatten="stringify")
        assert tbl.schema() == {"s.a": "integer", "m": "string"}
        assert tbl.view().to_columns() == {"s.a": [1], "m": ['{"a":1,"b":2}']}

    def test_map_pivots_while_struct_stringifies(self):
        tbl = Table(self.mixed(), struct_flatten="stringify", map_flatten="pivot")
        assert tbl.schema() == {"s": "string", "m.a": "integer", "m.b": "integer"}
        assert tbl.view().to_columns() == {
            "s": ['{"a":1}'],
            "m.a": [1],
            "m.b": [2],
        }

    def test_unset_map_flatten_follows_struct_flatten(self):
        tbl = Table(self.mixed(), struct_flatten="stringify")
        assert tbl.view().to_columns() == {"s": ['{"a":1}'], "m": ['{"a":1,"b":2}']}
        assert Table(self.mixed()).schema() == {
            "s.a": "integer",
            "m.a": "integer",
            "m.b": "integer",
        }

    def test_map_inside_pivoted_struct_stringifies(self):
        data = pa.table(
            {
                "s": pa.array(
                    [{"a": 1, "m": [("k", 1)]}],
                    type=pa.struct([("a", pa.int64()), ("m", self.map_type)]),
                )
            }
        )

        assert Table(data, map_flatten="stringify").view().to_columns() == {
            "s.a": [1],
            "s.m": ['{"k":1}'],
        }

    def test_struct_under_pivoted_map_stringifies(self):
        data = pa.table(
            {
                "n": pa.array(
                    [[("k", {"x": 1})]],
                    type=pa.map_(pa.string(), pa.struct([("x", pa.int64())])),
                )
            }
        )

        tbl = Table(data, struct_flatten="stringify", map_flatten="pivot")
        assert tbl.view().to_columns() == {"n.k": ['{"x":1}']}

    def test_integer_keys_stringify_but_do_not_pivot(self):
        data = pa.table(
            {"m": pa.array([[(1, "x")]], type=pa.map_(pa.int32(), pa.string()))}
        )

        assert Table(data, map_flatten="stringify").view().to_columns() == {
            "m": ['{"1":"x"}']
        }

        with pytest.raises(psp.PerspectiveError, match=r"`int32`"):
            Table(data, map_flatten="pivot")

    def test_list_of_maps_explodes_then_stringifies(self):
        data = pa.table(
            {
                "id": pa.array([1], type=pa.int64()),
                "l": pa.array(
                    [[[("a", 1)], [("a", 2)]]], type=pa.list_(self.map_type)
                ),
            }
        )

        assert Table(data, map_flatten="stringify").view().to_columns() == {
            "id": [1, 1],
            "l": ['{"a":1}', '{"a":2}'],
        }

    def test_mode_persists_across_update_on_a_schema_table(self):
        tbl = Table({"m": "string"}, map_flatten="stringify")
        tbl.update(
            arrow_bytes(
                pa.table({"m": pa.array([[("a", 1)]], type=self.map_type)})
            )
        )

        assert tbl.view().to_columns() == {"m": ['{"a":1}']}

    def test_unknown_value_is_rejected(self):
        with pytest.raises(ValueError, match=r"map_flatten"):
            Table(self.mixed(), map_flatten="bogus")


class TestTableArrowStringifyTemporal(object):
    us_utc = pa.timestamp("us", tz="UTC")
    instant_ms = 1704164645000
    instant_us = 1704164645000006

    def flat_json(self, column, **options):
        tbl = Table(pa.table({"v": column}), **options)
        return json.loads(tbl.view().to_columns_string())["v"]

    def test_list_of_timestamps_matches_the_flat_column(self):
        column = pa.array([[self.instant_us]], pa.list_(self.us_utc))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify")
        assert tbl.schema() == {"v": "string"}
        assert tbl.view().to_columns() == {"v": ["[1704164645000]"]}
        flat = pa.array([self.instant_us], self.us_utc)
        assert self.flat_json(flat) == [self.instant_ms]

    def test_list_of_structs_with_timestamps(self):
        item = pa.struct([("ts", self.us_utc), ("x", pa.int64())])
        column = pa.array([[{"ts": self.instant_us, "x": 1}]], pa.list_(item))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify")
        assert tbl.view().to_columns() == {
            "v": ['[{"ts":1704164645000,"x":1}]']
        }

    def test_struct_with_timestamp(self):
        item = pa.struct([("ts", pa.timestamp("ms"))])
        column = pa.array([{"ts": 1704164645006}], item)
        tbl = Table(pa.table({"v": column}), struct_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ['{"ts":1704164645006}']}

    def test_every_unit_truncates_like_the_flat_path(self):
        units = {
            "s": 1704164645,
            "ms": 1704164645006,
            "us": 1704164645006007,
            "ns": 1704164645006007008,
        }

        for unit, value in units.items():
            column = pa.array([[value]], pa.list_(pa.timestamp(unit)))
            tbl = Table(pa.table({"v": column}), list_flatten="stringify")
            flat = self.flat_json(pa.array([value], pa.timestamp(unit)))
            assert tbl.view().to_columns() == {"v": [json.dumps(flat)]}

    def test_timezone_is_ignored(self):
        naive = pa.array([[self.instant_us]], pa.list_(pa.timestamp("us")))
        zoned = pa.array(
            [[self.instant_us]],
            pa.list_(pa.timestamp("us", tz="America/New_York")),
        )

        for column in (naive, zoned):
            tbl = Table(pa.table({"v": column}), list_flatten="stringify")
            assert tbl.view().to_columns() == {"v": ["[1704164645000]"]}

    def test_before_the_epoch(self):
        column = pa.array([[-1]], pa.list_(pa.timestamp("ms")))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ["[-1]"]}

    def test_dates_match_the_flat_column(self):
        for column, flat in (
            (pa.array([[19724]], pa.list_(pa.date32())), pa.array([19724], pa.date32())),
            (
                pa.array([[1704153600000]], pa.list_(pa.date64())),
                pa.array([1704153600000], pa.date64()),
            ),
        ):
            tbl = Table(pa.table({"v": column}), list_flatten="stringify")
            assert tbl.view().to_columns() == {"v": ["[1704153600000]"]}
            assert self.flat_json(flat) == [1704153600000]

    def test_null_timestamp_element(self):
        column = pa.array([[self.instant_us, None]], pa.list_(self.us_utc))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ["[1704164645000,null]"]}

    def test_map_of_timestamps(self):
        column = pa.array(
            [[("k", self.instant_us)]], pa.map_(pa.string(), self.us_utc)
        )

        tbl = Table(pa.table({"v": column}), map_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ['{"k":1704164645000}']}

    def test_formatted_output_is_unchanged(self):
        tbl = Table(pa.table({"v": pa.array([self.instant_us], self.us_utc)}))
        assert json.loads(tbl.view().to_columns_string(formatted=True)) == {
            "v": ["2024-01-02 03:04:05.000"]
        }

    def test_time_and_duration_are_unit_counts(self):
        time = pa.array([[11045000006]], pa.list_(pa.time64("us")))
        duration = pa.array([[1500]], pa.list_(pa.duration("ns")))
        for column, text in ((time, "[11045000006]"), (duration, "[1500]")):
            tbl = Table(pa.table({"v": column}), list_flatten="stringify")
            assert tbl.view().to_columns() == {"v": [text]}

    def test_decimal_is_text(self):
        column = pa.array([[Decimal("1.50")]], pa.list_(pa.decimal128(10, 2)))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ['["1.50"]']}

    def test_binary_is_base64(self):
        column = pa.array([[b"hi"]], pa.list_(pa.binary()))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ['["aGk="]']}

    def test_non_finite_floats_are_null(self):
        values = [float("inf"), float("-inf"), float("nan"), 1.5]
        column = pa.array([values], pa.list_(pa.float64()))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ["[null,null,null,1.5]"]}
        assert self.flat_json(pa.array(values, pa.float64())) == [
            None,
            None,
            None,
            1.5,
        ]

    def test_fixed_size_list_inside_a_struct(self):
        item = pa.struct([("p", pa.list_(pa.int32(), 2))])
        column = pa.array([{"p": [1, 2]}], item)
        tbl = Table(pa.table({"v": column}), struct_flatten="stringify")
        assert tbl.view().to_columns() == {"v": ['{"p":[1,2]}']}


class TestTableArrowStringifyFormatted(object):
    us_utc = pa.timestamp("us", tz="UTC")
    instant_us = 1704164645000006
    text = "2024-01-02 03:04:05.000"

    def struct_column(self):
        return pa.array(
            [{"ts": self.instant_us, "d": 19724, "x": 1}],
            pa.struct([("ts", self.us_utc), ("d", pa.date32()), ("x", pa.int64())]),
        )

    def map_column(self):
        return pa.array(
            [[("k", self.instant_us)]], pa.map_(pa.string(), self.us_utc)
        )

    def test_struct_formats_datetimes(self):
        tbl = Table(
            pa.table({"v": self.struct_column()}),
            struct_flatten="stringify_formatted",
        )

        assert tbl.schema() == {"v": "string"}
        assert tbl.view().to_columns() == {
            "v": ['{"ts":"2024-01-02 03:04:05.000","d":"2024-01-02","x":1}']
        }

    def test_matches_formatted_to_json(self):
        flat = Table(
            pa.table(
                {
                    "ts": pa.array([self.instant_us], self.us_utc),
                    "d": pa.array([19724], pa.date32()),
                }
            )
        )

        assert json.loads(flat.view().to_columns_string(formatted=True)) == {
            "ts": [self.text],
            "d": ["2024-01-02"],
        }

    def test_map_formats_datetimes(self):
        tbl = Table(
            pa.table({"v": self.map_column()}), map_flatten="stringify_formatted"
        )

        assert tbl.view().to_columns() == {
            "v": ['{"k":"2024-01-02 03:04:05.000"}']
        }

    def test_unset_map_flatten_follows_formatted_struct(self):
        tbl = Table(
            pa.table({"v": self.map_column()}),
            struct_flatten="stringify_formatted",
        )

        assert tbl.view().to_columns() == {
            "v": ['{"k":"2024-01-02 03:04:05.000"}']
        }

    def test_explicit_map_flatten_overrides_formatted_struct(self):
        tbl = Table(
            pa.table({"v": self.map_column()}),
            struct_flatten="stringify_formatted",
            map_flatten="stringify",
        )

        assert tbl.view().to_columns() == {"v": ['{"k":1704164645000}']}

    def test_each_exploded_struct_is_formatted(self):
        item = pa.struct([("ts", self.us_utc)])
        column = pa.array(
            [[{"ts": self.instant_us}, {"ts": self.instant_us}]], pa.list_(item)
        )

        tbl = Table(
            pa.table({"v": column}), struct_flatten="stringify_formatted"
        )

        assert tbl.view().to_columns() == {
            "v": ['{"ts":"2024-01-02 03:04:05.000"}'] * 2
        }

    def test_outer_list_stringify_wins(self):
        item = pa.struct([("ts", self.us_utc)])
        column = pa.array([[{"ts": self.instant_us}]], pa.list_(item))
        tbl = Table(
            pa.table({"v": column}),
            list_flatten="stringify",
            struct_flatten="stringify_formatted",
        )

        assert tbl.view().to_columns() == {"v": ['[{"ts":1704164645000}]']}

    def test_list_formats_datetimes(self):
        column = pa.array([[self.instant_us, None]], pa.list_(self.us_utc))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify_formatted")
        assert tbl.schema() == {"v": "string"}
        assert tbl.view().to_columns() == {
            "v": ['["2024-01-02 03:04:05.000",null]']
        }

    def test_list_of_structs_formats_through_the_outer_layer(self):
        item = pa.struct([("ts", self.us_utc)])
        column = pa.array([[{"ts": self.instant_us}]], pa.list_(item))
        tbl = Table(pa.table({"v": column}), list_flatten="stringify_formatted")
        assert tbl.view().to_columns() == {
            "v": ['[{"ts":"2024-01-02 03:04:05.000"}]']
        }

    def test_json_arrays_are_unchanged(self):
        tbl = Table([{"y": [1, 2]}], list_flatten="stringify_formatted")
        assert tbl.view().to_columns() == {"y": ["[1,2]"]}

    def test_json_objects_are_unchanged(self):
        tbl = Table([{"s": {"a": 1}}], struct_flatten="stringify_formatted")
        assert tbl.view().to_columns() == {"s": ['{"a":1}']}

    def test_persists_across_update_on_a_schema_table(self):
        tbl = Table({"v": "string"}, struct_flatten="stringify_formatted")
        tbl.update(arrow_bytes(pa.table({"v": self.struct_column()})))
        assert tbl.view().to_columns() == {
            "v": ['{"ts":"2024-01-02 03:04:05.000","d":"2024-01-02","x":1}']
        }