-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
schemas.py
1616 lines (1500 loc) · 53.8 KB
/
schemas.py
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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=too-many-lines
from __future__ import annotations
import inspect
from typing import Any, TYPE_CHECKING
from flask_babel import gettext as _
from marshmallow import EXCLUDE, fields, post_load, Schema, validate
from marshmallow.validate import Length, Range
from superset import app
from superset.common.chart_data import ChartDataResultFormat, ChartDataResultType
from superset.db_engine_specs.base import builtin_time_grains
from superset.utils import pandas_postprocessing, schema as utils
from superset.utils.core import (
AnnotationType,
DatasourceType,
FilterOperator,
PostProcessingBoxplotWhiskerType,
PostProcessingContributionOrientation,
)
if TYPE_CHECKING:
from superset.common.query_context import QueryContext
from superset.common.query_context_factory import QueryContextFactory
config = app.config
#
# RISON/JSON schemas for query parameters
#
get_delete_ids_schema = {"type": "array", "items": {"type": "integer"}}
width_height_schema = {
"type": "array",
"items": {"type": "integer"},
}
thumbnail_query_schema = {
"type": "object",
"properties": {"force": {"type": "boolean"}},
}
screenshot_query_schema = {
"type": "object",
"properties": {
"force": {"type": "boolean"},
"window_size": width_height_schema,
"thumb_size": width_height_schema,
},
}
get_export_ids_schema = {"type": "array", "items": {"type": "integer"}}
get_fav_star_ids_schema = {"type": "array", "items": {"type": "integer"}}
#
# Column schema descriptions
#
id_description = "The id of the chart."
slice_name_description = "The name of the chart."
description_description = "A description of the chart propose."
viz_type_description = "The type of chart visualization used."
owners_description = (
"Owner are users ids allowed to delete or change this chart. "
"If left empty you will be one of the owners of the chart."
)
params_description = (
"Parameters are generated dynamically when clicking the save "
"or overwrite button in the explore view. "
"This JSON object for power users who may want to alter specific parameters."
)
query_context_description = (
"The query context represents the queries that need to run "
"in order to generate the data the visualization, and in what "
"format the data should be returned."
)
query_context_generation_description = (
"The query context generation represents whether the query_context"
"is user generated or not so that it does not update user modified"
"state."
)
cache_timeout_description = (
"Duration (in seconds) of the caching timeout "
"for this chart. Note this defaults to the datasource/table"
" timeout if undefined."
)
datasource_id_description = (
"The id of the dataset/datasource this new chart will use. "
"A complete datasource identification needs `datasource_id` "
"and `datasource_type`."
)
datasource_uid_description = (
"The uid of the dataset/datasource this new chart will use. "
"A complete datasource identification needs `datasource_uid` "
)
datasource_type_description = (
"The type of dataset/datasource identified on `datasource_id`."
)
datasource_name_description = "The datasource name."
dashboards_description = "A list of dashboards to include this new chart to."
changed_on_description = "The ISO date that the chart was last changed."
slice_url_description = "The URL of the chart."
form_data_description = (
"Form data from the Explore controls used to form the chart's data query."
)
description_markeddown_description = "Sanitized HTML version of the chart description."
owners_name_description = "Name of an owner of the chart."
certified_by_description = "Person or group that has certified this chart"
certification_details_description = "Details of the certification"
tags_description = "Tags to be associated with the chart"
openapi_spec_methods_override = {
"get": {"get": {"summary": "Get a chart detail information"}},
"get_list": {
"get": {
"summary": "Get a list of charts",
"description": "Gets a list of charts, use Rison or JSON query "
"parameters for filtering, sorting, pagination and "
" for selecting specific columns and metadata.",
}
},
"info": {"get": {"summary": "Get metadata information about this API resource"}},
"related": {
"get": {
"description": "Get a list of all possible owners for a chart. "
"Use `owners` has the `column_name` parameter"
}
},
}
class ChartEntityResponseSchema(Schema):
"""
Schema for a chart object
"""
id = fields.Integer(metadata={"description": id_description})
slice_name = fields.String(metadata={"description": slice_name_description})
cache_timeout = fields.Integer(metadata={"description": cache_timeout_description})
changed_on = fields.DateTime(metadata={"description": changed_on_description})
description = fields.String(metadata={"description": description_description})
description_markeddown = fields.String(
metadata={"description": description_markeddown_description}
)
form_data = fields.Dict(metadata={"description": form_data_description})
slice_url = fields.String(metadata={"description": slice_url_description})
certified_by = fields.String(metadata={"description": certified_by_description})
certification_details = fields.String(
metadata={"description": certification_details_description}
)
class ChartPostSchema(Schema):
"""
Schema to add a new chart.
"""
slice_name = fields.String(
metadata={"description": slice_name_description},
required=True,
validate=Length(1, 250),
)
description = fields.String(
metadata={"description": description_description}, allow_none=True
)
viz_type = fields.String(
metadata={
"description": viz_type_description,
"example": ["bar", "area", "table"],
},
validate=Length(0, 250),
)
owners = fields.List(fields.Integer(metadata={"description": owners_description}))
params = fields.String(
metadata={"description": params_description},
allow_none=True,
validate=utils.validate_json,
)
query_context = fields.String(
metadata={"description": query_context_description},
allow_none=True,
validate=utils.validate_json,
)
query_context_generation = fields.Boolean(
metadata={"description": query_context_generation_description}, allow_none=True
)
cache_timeout = fields.Integer(
metadata={"description": cache_timeout_description}, allow_none=True
)
datasource_id = fields.Integer(
metadata={"description": datasource_id_description}, required=True
)
datasource_type = fields.String(
metadata={"description": datasource_type_description},
validate=validate.OneOf(choices=[ds.value for ds in DatasourceType]),
required=True,
)
datasource_name = fields.String(
metadata={"description": datasource_name_description}, allow_none=True
)
dashboards = fields.List(
fields.Integer(metadata={"description": dashboards_description})
)
certified_by = fields.String(
metadata={"description": certified_by_description}, allow_none=True
)
certification_details = fields.String(
metadata={"description": certification_details_description}, allow_none=True
)
is_managed_externally = fields.Boolean(allow_none=True, dump_default=False)
external_url = fields.String(allow_none=True)
class ChartPutSchema(Schema):
"""
Schema to update or patch a chart
"""
slice_name = fields.String(
metadata={"description": slice_name_description},
allow_none=True,
validate=Length(0, 250),
)
description = fields.String(
metadata={"description": description_description}, allow_none=True
)
viz_type = fields.String(
metadata={
"description": viz_type_description,
"example": ["bar", "area", "table"],
},
allow_none=True,
validate=Length(0, 250),
)
owners = fields.List(fields.Integer(metadata={"description": owners_description}))
params = fields.String(
metadata={"description": params_description}, allow_none=True
)
query_context = fields.String(
metadata={"description": query_context_description}, allow_none=True
)
query_context_generation = fields.Boolean(
metadata={"description": query_context_generation_description}, allow_none=True
)
cache_timeout = fields.Integer(
metadata={"description": cache_timeout_description}, allow_none=True
)
datasource_id = fields.Integer(
metadata={"description": datasource_id_description}, allow_none=True
)
datasource_type = fields.String(
metadata={"description": datasource_type_description},
validate=validate.OneOf(choices=[ds.value for ds in DatasourceType]),
allow_none=True,
)
dashboards = fields.List(
fields.Integer(metadata={"description": dashboards_description})
)
certified_by = fields.String(
metadata={"description": certified_by_description}, allow_none=True
)
certification_details = fields.String(
metadata={"description": certification_details_description}, allow_none=True
)
is_managed_externally = fields.Boolean(allow_none=True, dump_default=False)
external_url = fields.String(allow_none=True)
tags = fields.List(fields.Integer(metadata={"description": tags_description}))
class ChartGetDatasourceObjectDataResponseSchema(Schema):
datasource_id = fields.Integer(
metadata={"description": "The datasource identifier"}
)
datasource_type = fields.Integer(metadata={"description": "The datasource type"})
class ChartGetDatasourceObjectResponseSchema(Schema):
label = fields.String(metadata={"description": "The name of the datasource"})
value = fields.Nested(ChartGetDatasourceObjectDataResponseSchema)
class ChartGetDatasourceResponseSchema(Schema):
count = fields.Integer(metadata={"description": "The total number of datasources"})
result = fields.Nested(ChartGetDatasourceObjectResponseSchema)
class ChartCacheScreenshotResponseSchema(Schema):
cache_key = fields.String(metadata={"description": "The cache key"})
chart_url = fields.String(metadata={"description": "The url to render the chart"})
image_url = fields.String(
metadata={"description": "The url to fetch the screenshot"}
)
class ChartDataColumnSchema(Schema):
column_name = fields.String(
metadata={"description": "The name of the target column", "example": "mycol"},
)
type = fields.String(
metadata={"description": "Type of target column", "example": "BIGINT"}
)
class ChartDataAdhocMetricSchema(Schema):
"""
Ad-hoc metrics are used to define metrics outside the datasource.
"""
expressionType = fields.String( # noqa: N815
metadata={"description": "Simple or SQL metric", "example": "SQL"},
required=True,
validate=validate.OneOf(choices=("SIMPLE", "SQL")),
)
aggregate = fields.String(
metadata={
"description": "Aggregation operator."
"Only required for simple expression types."
},
validate=validate.OneOf(
choices=("AVG", "COUNT", "COUNT_DISTINCT", "MAX", "MIN", "SUM")
),
)
column = fields.Nested(ChartDataColumnSchema)
sqlExpression = fields.String( # noqa: N815
metadata={
"description": "The metric as defined by a SQL aggregate expression. "
"Only required for SQL expression type.",
"example": "SUM(weight * observations) / SUM(weight)",
},
)
label = fields.String(
metadata={
"description": "Label for the metric. Is automatically generated unless"
"hasCustomLabel is true, in which case label must be defined.",
"example": "Weighted observations",
},
)
hasCustomLabel = fields.Boolean( # noqa: N815
metadata={
"description": "When false, the label will be automatically generated based " # noqa: E501
"on the aggregate expression. When true, a custom label has to be specified.", # noqa: E501
"example": True,
},
)
optionName = fields.String( # noqa: N815
metadata={
"description": "Unique identifier. Can be any string value, as long as all "
"metrics have a unique identifier. If undefined, a random name"
"will be generated.",
"example": "metric_aec60732-fac0-4b17-b736-93f1a5c93e30",
},
)
timeGrain = fields.String( # noqa: N815
metadata={
"description": "Optional time grain for temporal filters",
"example": "PT1M",
},
)
isExtra = fields.Boolean( # noqa: N815
metadata={
"description": "Indicates if the filter has been added by a filter component " # noqa: E501
"as opposed to being a part of the original query."
}
)
class ChartDataAggregateConfigField(fields.Dict):
def __init__(self) -> None:
super().__init__(
metadata={
"description": "The keys are the name of the aggregate column to be "
"created, and the values specify the details of how to apply the "
"aggregation. If an operator requires additional options, "
"these can be passed here to be unpacked in the operator call. The "
"following numpy operators are supported: average, argmin, argmax, "
"cumsum, cumprod, max, mean, median, nansum, nanmin, nanmax, nanmean, "
"nanmedian, min, percentile, prod, product, std, sum, var. Any options "
"required by the operator can be passed to the `options` object.\n"
"\n"
"In the example, a new column `first_quantile` is created based on "
"values in the column `my_col` using the `percentile` operator with "
"the `q=0.25` parameter.",
"example": {
"first_quantile": {
"operator": "percentile",
"column": "my_col",
"options": {"q": 0.25},
}
},
},
)
class ChartDataPostProcessingOperationOptionsSchema(Schema):
pass
class ChartDataAggregateOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Aggregate operation config.
"""
groupby = (
fields.List(
fields.String(
allow_none=False,
metadata={"description": "Columns by which to group by"},
),
minLength=1,
required=True,
),
)
aggregates = ChartDataAggregateConfigField()
class ChartDataRollingOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Rolling operation config.
"""
columns = (
fields.Dict(
metadata={
"description": "columns on which to perform rolling, mapping source "
"column to target column. For instance, `{'y': 'y'}` will replace the "
"column `y` with the rolling value in `y`, while `{'y': 'y2'}` will add " # noqa: E501
"a column `y2` based on rolling values calculated from `y`, leaving the " # noqa: E501
"original column `y` unchanged.",
"example": {"weekly_rolling_sales": "sales"},
},
),
)
rolling_type = fields.String(
metadata={
"description": "Type of rolling window. Any numpy function will work.",
"example": "percentile",
},
validate=validate.OneOf(
choices=(
"average",
"argmin",
"argmax",
"cumsum",
"cumprod",
"max",
"mean",
"median",
"nansum",
"nanmin",
"nanmax",
"nanmean",
"nanmedian",
"nanpercentile",
"min",
"percentile",
"prod",
"product",
"std",
"sum",
"var",
)
),
required=True,
)
window = fields.Integer(
metadata={"description": "Size of the rolling window in days.", "example": 7},
required=True,
)
rolling_type_options = fields.Dict(
metadata={
"description": "Optional options to pass to rolling method. Needed for "
"e.g. quantile operation.",
"example": {},
},
)
center = fields.Boolean(
metadata={
"description": "Should the label be at the center of the window."
"Default: `false`",
"example": False,
},
)
win_type = fields.String(
metadata={
"description": "Type of window function. See "
"[SciPy window functions](https://docs.scipy.org/doc/scipy/reference "
"/signal.windows.html#module-scipy.signal.windows) "
"for more details. Some window functions require passing "
"additional parameters to `rolling_type_options`. For instance, "
"to use `gaussian`, the parameter `std` needs to be provided."
""
},
validate=validate.OneOf(
choices=(
"boxcar",
"triang",
"blackman",
"hamming",
"bartlett",
"parzen",
"bohman",
"blackmanharris",
"nuttall",
"barthann",
"kaiser",
"gaussian",
"general_gaussian",
"slepian",
"exponential",
)
),
)
min_periods = fields.Integer(
metadata={
"description": "The minimum amount of periods required for a row to be "
"included in the result set.",
"example": 7,
},
)
class ChartDataSelectOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Sort operation config.
"""
columns = fields.List(
fields.String(),
metadata={
"description": "Columns which to select from the input data, in the desired " # noqa: E501
"order. If columns are renamed, the original column name should be "
"referenced here.",
"example": ["country", "gender", "age"],
},
)
exclude = fields.List(
fields.String(),
metadata={
"description": "Columns to exclude from selection.",
"example": ["my_temp_column"],
},
)
rename = fields.List(
fields.Dict(),
metadata={
"description": "columns which to rename, mapping source column to target "
"column. For instance, `{'y': 'y2'}` will rename the column `y` to `y2`.",
"example": [{"age": "average_age"}],
},
)
class ChartDataSortOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Sort operation config.
"""
columns = fields.Dict(
metadata={
"description": "columns by by which to sort. The key specifies the column "
"name, value specifies if sorting in ascending order.",
"example": {"country": True, "gender": False},
},
required=True,
)
aggregates = ChartDataAggregateConfigField()
class ChartDataContributionOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Contribution operation config.
"""
orientation = fields.String(
metadata={
"description": "Should cell values be calculated across the row or column.",
"example": "row",
},
required=True,
validate=validate.OneOf(
choices=[val.value for val in PostProcessingContributionOrientation]
),
)
class ChartDataProphetOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Prophet operation config.
"""
time_grain = fields.String(
metadata={
"description": "Time grain used to specify time period increments in "
"prediction. Supports "
"[ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) durations.",
"example": "P1D",
},
validate=validate.OneOf(
choices=[
i
for i in {**builtin_time_grains, **config["TIME_GRAIN_ADDONS"]}.keys()
if i
]
),
required=True,
)
periods = fields.Integer(
metadata={
"description": "Time periods (in units of `time_grain`) to predict into "
"the future",
"example": 7,
},
min=0,
required=True,
)
confidence_interval = fields.Float(
metadata={
"description": "Width of predicted confidence interval",
"example": 0.8,
},
validate=[
Range(
min=0,
max=1,
min_inclusive=False,
max_inclusive=False,
error=_("`confidence_interval` must be between 0 and 1 (exclusive)"),
)
],
required=True,
)
yearly_seasonality = fields.Raw(
# TODO: add correct union type once supported by Marshmallow
metadata={
"description": "Should yearly seasonality be applied. "
"An integer value will specify Fourier order of seasonality, `None` will "
"automatically detect seasonality.",
"example": False,
},
)
weekly_seasonality = fields.Raw(
# TODO: add correct union type once supported by Marshmallow
metadata={
"description": "Should weekly seasonality be applied. "
"An integer value will specify Fourier order of seasonality, `None` will "
"automatically detect seasonality.",
"example": False,
},
)
monthly_seasonality = fields.Raw(
# TODO: add correct union type once supported by Marshmallow
metadata={
"description": "Should monthly seasonality be applied. "
"An integer value will specify Fourier order of seasonality, `None` will "
"automatically detect seasonality.",
"example": False,
},
)
class ChartDataBoxplotOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Boxplot operation config.
"""
groupby = fields.List(
fields.String(
metadata={"description": "Columns by which to group the query."},
),
allow_none=True,
)
metrics = fields.List(
fields.Raw(),
metadata={
"description": "Aggregate expressions. Metrics can be passed as both "
"references to datasource metrics (strings), or ad-hoc metrics"
"which are defined only within the query object. See "
"`ChartDataAdhocMetricSchema` for the structure of ad-hoc metrics. "
"When metrics is undefined or null, the query is executed without a groupby. " # noqa: E501
"However, when metrics is an array (length >= 0), a groupby clause is added " # noqa: E501
"to the query."
},
allow_none=True,
)
whisker_type = fields.String(
metadata={
"description": "Whisker type. Any numpy function will work.",
"example": "tukey",
},
validate=validate.OneOf(
choices=([val.value for val in PostProcessingBoxplotWhiskerType])
),
required=True,
)
percentiles = fields.Tuple(
(
fields.Float(
metadata={"description": "Lower percentile"},
validate=[
Range(
min=0,
max=100,
min_inclusive=False,
max_inclusive=False,
error=_(
"lower percentile must be greater than 0 and less "
"than 100. Must be lower than upper percentile."
),
),
],
),
fields.Float(
metadata={"description": "Upper percentile"},
validate=[
Range(
min=0,
max=100,
min_inclusive=False,
max_inclusive=False,
error=_(
"upper percentile must be greater than 0 and less "
"than 100. Must be higher than lower percentile."
),
),
],
),
),
metadata={
"description": "Upper and lower percentiles for percentile whisker type.",
"example": [1, 99],
},
)
class ChartDataPivotOptionsSchema(ChartDataPostProcessingOperationOptionsSchema):
"""
Pivot operation config.
"""
index = (
fields.List(
fields.String(allow_none=False),
metadata={"description": "Columns to group by on the table index (=rows)"},
minLength=1,
required=True,
),
)
columns = fields.List(
fields.String(allow_none=False),
metadata={"description": "Columns to group by on the table columns"},
)
metric_fill_value = fields.Number(
metadata={
"description": "Value to replace missing values with in "
"aggregate calculations."
},
)
column_fill_value = fields.String(
metadata={"description": "Value to replace missing pivot columns names with."}
)
drop_missing_columns = fields.Boolean(
metadata={
"description": "Do not include columns whose entries are all missing "
"(default: `true`)."
},
)
marginal_distributions = fields.Boolean(
metadata={"description": "Add totals for row/column. (default: `false`)"},
)
marginal_distribution_name = fields.String(
metadata={
"description": "Name of marginal distribution row/column. "
"(default: `All`)"
},
)
aggregates = ChartDataAggregateConfigField()
class ChartDataGeohashDecodeOptionsSchema(
ChartDataPostProcessingOperationOptionsSchema
):
"""
Geohash decode operation config.
"""
geohash = fields.String(
metadata={"description": "Name of source column containing geohash string"},
required=True,
)
latitude = fields.String(
metadata={"description": "Name of target column for decoded latitude"},
required=True,
)
longitude = fields.String(
metadata={"description": "Name of target column for decoded longitude"},
required=True,
)
class ChartDataGeohashEncodeOptionsSchema(
ChartDataPostProcessingOperationOptionsSchema
):
"""
Geohash encode operation config.
"""
latitude = fields.String(
metadata={"description": "Name of source latitude column"},
required=True,
)
longitude = fields.String(
metadata={"description": "Name of source longitude column"},
required=True,
)
geohash = fields.String(
metadata={"description": "Name of target column for encoded geohash string"},
required=True,
)
class ChartDataGeodeticParseOptionsSchema(
ChartDataPostProcessingOperationOptionsSchema
):
"""
Geodetic point string parsing operation config.
"""
geodetic = fields.String(
metadata={
"description": "Name of source column containing geodetic point strings"
},
required=True,
)
latitude = fields.String(
metadata={"description": "Name of target column for decoded latitude"},
required=True,
)
longitude = fields.String(
metadata={"description": "Name of target column for decoded longitude"},
required=True,
)
altitude = fields.String(
metadata={
"description": "Name of target column for decoded altitude. If omitted, "
"altitude information in geodetic string is ignored."
},
)
class ChartDataPostProcessingOperationSchema(Schema):
operation = fields.String(
metadata={
"description": "Post processing operation type",
"example": "aggregate",
},
required=True,
validate=validate.OneOf(
choices=[
name
for name, value in inspect.getmembers(
pandas_postprocessing, inspect.isfunction
)
]
),
)
options = fields.Dict(
metadata={
"description": "Options specifying how to perform the operation. Please "
"refer to the respective post processing operation option schemas. "
"For example, `ChartDataPostProcessingOperationOptions` specifies "
"the required options for the pivot operation.",
"example": {
"groupby": ["country", "gender"],
"aggregates": {
"age_q1": {
"operator": "percentile",
"column": "age",
"options": {"q": 0.25},
},
"age_mean": {
"operator": "mean",
"column": "age",
},
},
},
},
)
class ChartDataFilterSchema(Schema):
col = fields.Raw(
metadata={
"description": "The column to filter by. Can be either a string (physical or " # noqa: E501
"saved expression) or an object (adhoc column)",
"example": "country",
},
required=True,
)
op = fields.String( # pylint: disable=invalid-name
metadata={"description": "The comparison operator.", "example": "IN"},
validate=utils.OneOfCaseInsensitive(
choices=[filter_op.value for filter_op in FilterOperator]
),
required=True,
)
val = fields.Raw(
metadata={
"description": "The value or values to compare against. Can be a string, "
"integer, decimal, None or list, depending on the operator.",
"example": ["China", "France", "Japan"],
},
allow_none=True,
)
grain = fields.String(
metadata={
"description": "Optional time grain for temporal filters",
"example": "PT1M",
},
)
isExtra = fields.Boolean( # noqa: N815
metadata={
"description": "Indicates if the filter has been added by a filter "
"component as opposed to being a part of the original query."
}
)
class ChartDataExtrasSchema(Schema):
relative_start = fields.String(
metadata={
"description": "Start time for relative time deltas. "
'Default: `config["DEFAULT_RELATIVE_START_TIME"]`'
},
validate=validate.OneOf(choices=("today", "now")),
)
relative_end = fields.String(
metadata={
"description": "End time for relative time deltas. "
'Default: `config["DEFAULT_RELATIVE_START_TIME"]`'
},
validate=validate.OneOf(choices=("today", "now")),
)
where = fields.String(
metadata={
"description": "WHERE clause to be added to queries using AND operator."
},
)
having = fields.String(
metadata={
"description": "HAVING clause to be added to aggregate queries using "
"AND operator."
},
)
time_grain_sqla = fields.String(
metadata={
"description": "To what level of granularity should the temporal column be "
"aggregated. Supports "
"[ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) durations.",
"example": "P1D",
},
validate=validate.OneOf(
choices=[
i
for i in {**builtin_time_grains, **config["TIME_GRAIN_ADDONS"]}.keys()
if i
]
),
allow_none=True,
)
instant_time_comparison_range = fields.String(
metadata={
"description": "This is only set using the new time comparison controls "
"that is made available in some plugins behind the experimental "
"feature flag."
},
allow_none=True,
)
class AnnotationLayerSchema(Schema):
annotationType = fields.String( # noqa: N815
metadata={"description": "Type of annotation layer"},
validate=validate.OneOf(choices=[ann.value for ann in AnnotationType]),