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# 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.
# isort:skip_file
from __future__ import annotations
import re
from datetime import datetime
from typing import Any, cast, Literal, NamedTuple, Optional, Union
from re import Pattern
from unittest.mock import Mock, patch
import pytest
import numpy as np
import pandas as pd
from flask.ctx import AppContext
from flask_appbuilder.security.sqla.models import Role
from pytest_mock import MockerFixture
from sqlalchemy.sql import text
from sqlalchemy.sql.elements import TextClause
from superset import db
from superset.connectors.sqla.models import SqlaTable, TableColumn, SqlMetric
from superset.constants import EMPTY_STRING, NULL_STRING
from superset.superset_typing import QueryObjectDict
from superset.db_engine_specs.bigquery import BigQueryEngineSpec
from superset.db_engine_specs.druid import DruidEngineSpec
from superset.exceptions import (
QueryObjectValidationError,
) # noqa: F401
from superset.models.core import Database
from superset.utils.core import (
AdhocMetricExpressionType,
FilterOperator,
GenericDataType,
)
from superset.utils.database import get_example_database
from tests.integration_tests.fixtures.birth_names_dashboard import (
load_birth_names_dashboard_with_slices, # noqa: F401
load_birth_names_data, # noqa: F401
)
from .base_tests import SupersetTestCase
from .conftest import only_postgresql
VIRTUAL_TABLE_INT_TYPES: dict[str, Pattern[str]] = {
"hive": re.compile(r"^INT_TYPE$"),
"mysql": re.compile("^LONGLONG$"),
"postgresql": re.compile(r"^INTEGER$"),
"presto": re.compile(r"^INTEGER$"),
"sqlite": re.compile(r"^INT$"),
}
VIRTUAL_TABLE_STRING_TYPES: dict[str, Pattern[str]] = {
"hive": re.compile(r"^STRING_TYPE$"),
"mysql": re.compile(r"^VAR_STRING$"),
"postgresql": re.compile(r"^STRING$"),
"presto": re.compile(r"^VARCHAR*"),
"sqlite": re.compile(r"^STRING$"),
}
class FilterTestCase(NamedTuple):
column: str
operator: str
value: Union[float, int, list[Any], str]
expected: Union[str, list[str]]
class TestDatabaseModel(SupersetTestCase):
def test_is_time_druid_time_col(self):
"""Druid has a special __time column"""
database = Database(database_name="druid_db", sqlalchemy_uri="druid://db")
tbl = SqlaTable(table_name="druid_tbl", database=database)
col = TableColumn(column_name="__time", type="INTEGER", table=tbl)
assert col.is_dttm is None
DruidEngineSpec.alter_new_orm_column(col)
assert col.is_dttm is True
col = TableColumn(column_name="__not_time", type="INTEGER", table=tbl)
assert col.is_temporal is False
def test_temporal_varchar(self):
"""Ensure a column with is_dttm set to true evaluates to is_temporal == True"""
database = get_example_database()
tbl = SqlaTable(table_name="test_tbl", database=database)
col = TableColumn(column_name="ds", type="VARCHAR", table=tbl)
# by default, VARCHAR should not be assumed to be temporal
assert col.is_temporal is False
# changing to `is_dttm = True`, calling `is_temporal` should return True
col.is_dttm = True
assert col.is_temporal is True
def test_db_column_types(self):
test_cases: dict[str, GenericDataType] = {
# string
"CHAR": GenericDataType.STRING,
"VARCHAR": GenericDataType.STRING,
"NVARCHAR": GenericDataType.STRING,
"STRING": GenericDataType.STRING,
"TEXT": GenericDataType.STRING,
"NTEXT": GenericDataType.STRING,
# numeric
"INTEGER": GenericDataType.NUMERIC,
"BIGINT": GenericDataType.NUMERIC,
"DECIMAL": GenericDataType.NUMERIC,
# temporal
"DATE": GenericDataType.TEMPORAL,
"DATETIME": GenericDataType.TEMPORAL,
"TIME": GenericDataType.TEMPORAL,
"TIMESTAMP": GenericDataType.TEMPORAL,
}
tbl = SqlaTable(table_name="col_type_test_tbl", database=get_example_database())
for str_type, db_col_type in test_cases.items():
col = TableColumn(column_name="foo", type=str_type, table=tbl)
assert col.is_temporal == (db_col_type == GenericDataType.TEMPORAL)
assert col.is_numeric == (db_col_type == GenericDataType.NUMERIC)
assert col.is_string == (db_col_type == GenericDataType.STRING)
for str_type, db_col_type in test_cases.items(): # noqa: B007
col = TableColumn(column_name="foo", type=str_type, table=tbl, is_dttm=True)
assert col.is_temporal
@patch("superset.jinja_context.get_username", return_value="abc")
def test_jinja_metrics_and_calc_columns(self, mock_username):
base_query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"columns": [
"user",
"expr",
{
"hasCustomLabel": True,
"label": "adhoc_column",
"sqlExpression": "'{{ 'foo_' + time_grain }}'",
},
],
"metrics": [
{
"hasCustomLabel": True,
"label": "adhoc_metric",
"expressionType": AdhocMetricExpressionType.SQL,
"sqlExpression": "SUM(case when user = '{{ 'user_' + "
"current_username() }}' then 1 else 0 end)",
},
"count_timegrain",
],
"is_timeseries": False,
"filter": [],
"extras": {"time_grain_sqla": "P1D"},
}
table = SqlaTable(
table_name="test_has_jinja_metric_and_expr",
sql="SELECT '{{ 'user_' + current_username() }}' as user, "
"'{{ 'xyz_' + time_grain }}' as time_grain",
database=get_example_database(),
)
TableColumn(
column_name="expr",
expression="case when '{{ current_username() }}' = 'abc' "
"then 'yes' else 'no' end",
type="VARCHAR(100)",
table=table,
)
SqlMetric(
metric_name="count_timegrain",
expression="count('{{ 'bar_' + time_grain }}')",
table=table,
)
db.session.commit()
sqla_query = table.get_sqla_query(**base_query_obj)
query = table.database.compile_sqla_query(sqla_query.sqla_query)
# assert virtual dataset
assert "SELECT\n 'user_abc' AS user,\n 'xyz_P1D' AS time_grain" in query
# assert dataset calculated column
assert "case when 'abc' = 'abc' then 'yes' else 'no' end" in query
# assert adhoc column
assert "'foo_P1D'" in query
# assert dataset saved metric
assert "count('bar_P1D')" in query
# assert adhoc metric
assert "SUM(CASE WHEN user = 'user_abc' THEN 1 ELSE 0 END)" in query
# Cleanup
db.session.delete(table)
db.session.commit()
@patch("superset.jinja_context.get_dataset_id_from_context")
def test_jinja_metric_macro(self, mock_dataset_id_from_context):
self.login(username="admin")
table = self.get_table(name="birth_names")
metric = SqlMetric(
metric_name="count_jinja_metric", expression="count(*)", table=table
)
db.session.commit()
base_query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"columns": [],
"metrics": [
{
"hasCustomLabel": True,
"label": "Metric using Jinja macro",
"expressionType": AdhocMetricExpressionType.SQL,
"sqlExpression": "{{ metric('count_jinja_metric') }}",
},
{
"hasCustomLabel": True,
"label": "Same but different",
"expressionType": AdhocMetricExpressionType.SQL,
"sqlExpression": "{{ metric('count_jinja_metric', "
+ str(table.id)
+ ") }}",
},
],
"is_timeseries": False,
"filter": [],
"extras": {"time_grain_sqla": "P1D"},
}
mock_dataset_id_from_context.return_value = table.id
sqla_query = table.get_sqla_query(**base_query_obj)
query = table.database.compile_sqla_query(sqla_query.sqla_query)
database = table.database
with database.get_sqla_engine() as engine:
quote = engine.dialect.identifier_preparer.quote_identifier
for metric_label in {"metric using jinja macro", "same but different"}:
assert f"count(*) as {quote(metric_label)}" in query.lower()
db.session.delete(metric)
db.session.commit()
def test_adhoc_metrics_and_calc_columns(self):
base_query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["user", "expr"],
"metrics": [
{
"expressionType": AdhocMetricExpressionType.SQL,
"sqlExpression": "(SELECT (SELECT * from birth_names) "
"from test_validate_adhoc_sql)",
"label": "adhoc_metrics",
}
],
"is_timeseries": False,
"filter": [],
}
table = SqlaTable(
table_name="test_validate_adhoc_sql", database=get_example_database()
)
db.session.commit()
with pytest.raises(QueryObjectValidationError):
table.get_sqla_query(**base_query_obj)
# Cleanup
db.session.delete(table)
db.session.commit()
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_where_operators(self):
filters: tuple[FilterTestCase, ...] = (
FilterTestCase("num", FilterOperator.IS_NULL, "", "IS NULL"),
FilterTestCase("num", FilterOperator.IS_NOT_NULL, "", "IS NOT NULL"),
# Some db backends translate true/false to 1/0
FilterTestCase("num", FilterOperator.IS_TRUE, "", ["IS 1", "IS true"]),
FilterTestCase("num", FilterOperator.IS_FALSE, "", ["IS 0", "IS false"]),
FilterTestCase("num", FilterOperator.GREATER_THAN, 0, "> 0"),
FilterTestCase("num", FilterOperator.GREATER_THAN_OR_EQUALS, 0, ">= 0"),
FilterTestCase("num", FilterOperator.LESS_THAN, 0, "< 0"),
FilterTestCase("num", FilterOperator.LESS_THAN_OR_EQUALS, 0, "<= 0"),
FilterTestCase("num", FilterOperator.EQUALS, 0, "= 0"),
FilterTestCase("num", FilterOperator.NOT_EQUALS, 0, "!= 0"),
FilterTestCase("num", FilterOperator.IN, ["1", "2"], "IN (1, 2)"),
FilterTestCase("num", FilterOperator.NOT_IN, ["1", "2"], "NOT IN (1, 2)"),
FilterTestCase(
"ds", FilterOperator.TEMPORAL_RANGE, "2020 : 2021", "2020-01-01"
),
)
table = self.get_table(name="birth_names")
for filter_ in filters:
query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["gender"],
"metrics": ["count"],
"is_timeseries": False,
"filter": [
{
"col": filter_.column,
"op": filter_.operator,
"val": filter_.value,
}
],
"extras": {},
}
sqla_query = table.get_sqla_query(**query_obj)
sql = table.database.compile_sqla_query(sqla_query.sqla_query)
if isinstance(filter_.expected, list):
assert any([candidate in sql for candidate in filter_.expected]) # noqa: C419
else:
assert filter_.expected in sql
@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
def test_boolean_type_where_operators(self):
table = self.get_table(name="birth_names")
db.session.add(
TableColumn(
column_name="boolean_gender",
expression="case when gender = 'boy' then True else False end",
type="BOOLEAN",
table=table,
)
)
query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["boolean_gender"],
"metrics": ["count"],
"is_timeseries": False,
"filter": [
{
"col": "boolean_gender",
"op": FilterOperator.IN,
"val": ["true", "false"],
}
],
"extras": {},
}
sqla_query = table.get_sqla_query(**query_obj)
sql = table.database.compile_sqla_query(sqla_query.sqla_query)
dialect = table.database.get_dialect()
operand = "(true, false)"
# override native_boolean=False behavior in MySQLCompiler
# https://github.com/sqlalchemy/sqlalchemy/blob/master/lib/sqlalchemy/dialects/mysql/base.py
if not dialect.supports_native_boolean and dialect.name != "mysql":
operand = "(1, 0)"
assert f"IN {operand}" in sql
def test_incorrect_jinja_syntax_raises_correct_exception(self):
query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["user"],
"metrics": [],
"is_timeseries": False,
"filter": [],
"extras": {},
}
# Table with Jinja callable.
table = SqlaTable(
table_name="test_table",
sql="SELECT '{{ abcd xyz + 1 ASDF }}' as user",
database=get_example_database(),
)
# TODO(villebro): make it work with presto
if get_example_database().backend != "presto":
with pytest.raises(QueryObjectValidationError):
table.get_sqla_query(**query_obj)
def test_query_format_strip_trailing_semicolon(self):
query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["user"],
"metrics": [],
"is_timeseries": False,
"filter": [],
"extras": {},
}
table = SqlaTable(
table_name="another_test_table",
sql="SELECT * from test_table;",
database=get_example_database(),
)
sqlaq = table.get_sqla_query(**query_obj)
sql = table.database.compile_sqla_query(sqlaq.sqla_query)
assert sql[-1] != ";"
def test_multiple_sql_statements_raises_exception(self):
base_query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["grp"],
"metrics": [],
"is_timeseries": False,
"filter": [],
}
table = SqlaTable(
table_name="test_multiple_sql_statements",
sql="SELECT 'foo' as grp, 1 as num; SELECT 'bar' as grp, 2 as num",
database=get_example_database(),
)
query_obj = dict(**base_query_obj, extras={})
with pytest.raises(QueryObjectValidationError):
table.get_sqla_query(**query_obj)
def test_dml_statement_raises_exception(self):
base_query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["grp"],
"metrics": [],
"is_timeseries": False,
"filter": [],
}
table = SqlaTable(
table_name="test_dml_statement",
sql="DELETE FROM foo",
database=get_example_database(),
)
query_obj = dict(**base_query_obj, extras={})
with pytest.raises(QueryObjectValidationError):
table.get_sqla_query(**query_obj)
def test_fetch_metadata_for_updated_virtual_table(self):
table = SqlaTable(
table_name="updated_sql_table",
database=get_example_database(),
sql="select 123 as intcol, 'abc' as strcol, 'abc' as mycase",
)
TableColumn(column_name="intcol", type="FLOAT", table=table)
TableColumn(column_name="oldcol", type="INT", table=table)
TableColumn(
column_name="expr",
expression="case when 1 then 1 else 0 end",
type="INT",
table=table,
)
TableColumn(
column_name="mycase",
expression="case when 1 then 1 else 0 end",
type="INT",
table=table,
)
# make sure the columns have been mapped properly
assert len(table.columns) == 4
table.fetch_metadata()
# assert that the removed column has been dropped and
# the physical and calculated columns are present
assert {col.column_name for col in table.columns} == {
"intcol",
"strcol",
"mycase",
"expr",
}
cols: dict[str, TableColumn] = {col.column_name: col for col in table.columns}
# assert that the type for intcol has been updated (asserting CI types)
backend = table.database.backend
assert VIRTUAL_TABLE_INT_TYPES[backend].match(cols["intcol"].type)
# assert that the expression has been replaced with the new physical column
assert cols["mycase"].expression == ""
assert VIRTUAL_TABLE_STRING_TYPES[backend].match(cols["mycase"].type)
assert cols["expr"].expression == "case when 1 then 1 else 0 end"
@patch("superset.models.core.Database.db_engine_spec", BigQueryEngineSpec)
def test_labels_expected_on_mutated_query(self):
query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["user"],
"metrics": [
{
"expressionType": "SIMPLE",
"column": {"column_name": "user"},
"aggregate": "COUNT_DISTINCT",
"label": "COUNT_DISTINCT(user)",
}
],
"is_timeseries": False,
"filter": [],
"extras": {},
}
database = Database(database_name="testdb", sqlalchemy_uri="sqlite://")
table = SqlaTable(table_name="bq_table", database=database)
db.session.add(database)
db.session.add(table)
db.session.commit()
sqlaq = table.get_sqla_query(**query_obj)
assert sqlaq.labels_expected == ["user", "COUNT_DISTINCT(user)"]
sql = table.database.compile_sqla_query(sqlaq.sqla_query)
# SHA-256 hash of "COUNT_DISTINCT(user)" starts with "01c94"
assert "COUNT_DISTINCT_user__01c94" in sql
db.session.delete(table)
db.session.delete(database)
db.session.commit()
@pytest.fixture
def text_column_table(app_context: AppContext):
table = SqlaTable(
table_name="text_column_table",
sql=(
"SELECT 'foo' as foo "
"UNION SELECT '' "
"UNION SELECT NULL "
"UNION SELECT 'null' "
"UNION SELECT '\"text in double quotes\"' "
"UNION SELECT '''text in single quotes''' "
"UNION SELECT 'double quotes \" in text' "
"UNION SELECT 'single quotes '' in text' "
),
database=get_example_database(),
)
TableColumn(column_name="foo", type="VARCHAR(255)", table=table)
SqlMetric(metric_name="count", expression="count(*)", table=table)
return table
def test_values_for_column_on_text_column(text_column_table):
# null value, empty string and text should be retrieved
with_null = text_column_table.values_for_column(column_name="foo", limit=10000)
assert None in with_null
assert len(with_null) == 8
def test_values_for_column_on_text_column_with_rls(text_column_table):
with patch.object(
text_column_table,
"get_sqla_row_level_filters",
return_value=[
TextClause("foo = 'foo'"),
],
):
with_rls = text_column_table.values_for_column(column_name="foo", limit=10000)
assert with_rls == ["foo"]
assert len(with_rls) == 1
def test_values_for_column_on_text_column_with_rls_no_values(text_column_table):
with patch.object(
text_column_table,
"get_sqla_row_level_filters",
return_value=[
TextClause("foo = 'bar'"),
],
):
with_rls = text_column_table.values_for_column(column_name="foo", limit=10000)
assert with_rls == []
assert len(with_rls) == 0
def test_filter_on_text_column(text_column_table):
table = text_column_table
# null value should be replaced
result_object = table.query(
{
"metrics": ["count"],
"filter": [{"col": "foo", "val": [NULL_STRING], "op": "IN"}],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
# also accept None value
result_object = table.query(
{
"metrics": ["count"],
"filter": [{"col": "foo", "val": [None], "op": "IN"}],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
# empty string should be replaced
result_object = table.query(
{
"metrics": ["count"],
"filter": [{"col": "foo", "val": [EMPTY_STRING], "op": "IN"}],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
# also accept "" string
result_object = table.query(
{
"metrics": ["count"],
"filter": [{"col": "foo", "val": [""], "op": "IN"}],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
# both replaced
result_object = table.query(
{
"metrics": ["count"],
"filter": [
{
"col": "foo",
"val": [EMPTY_STRING, NULL_STRING, "null", "foo"],
"op": "IN",
}
],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 4
# should filter text in double quotes
result_object = table.query(
{
"metrics": ["count"],
"filter": [
{
"col": "foo",
"val": ['"text in double quotes"'],
"op": "IN",
}
],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
# should filter text in single quotes
result_object = table.query(
{
"metrics": ["count"],
"filter": [
{
"col": "foo",
"val": ["'text in single quotes'"],
"op": "IN",
}
],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
# should filter text with double quote
result_object = table.query(
{
"metrics": ["count"],
"filter": [
{
"col": "foo",
"val": ['double quotes " in text'],
"op": "IN",
}
],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
# should filter text with single quote
result_object = table.query(
{
"metrics": ["count"],
"filter": [
{
"col": "foo",
"val": ["single quotes ' in text"],
"op": "IN",
}
],
"is_timeseries": False,
}
)
assert result_object.df["count"][0] == 1
@only_postgresql
def test_should_generate_closed_and_open_time_filter_range(login_as_admin):
table = SqlaTable(
table_name="temporal_column_table",
sql=(
"SELECT '2021-12-31'::timestamp as datetime_col "
"UNION SELECT '2022-01-01'::timestamp "
"UNION SELECT '2022-03-10'::timestamp "
"UNION SELECT '2023-01-01'::timestamp "
"UNION SELECT '2023-03-10'::timestamp "
),
database=get_example_database(),
)
TableColumn(
column_name="datetime_col",
type="TIMESTAMP",
table=table,
is_dttm=True,
)
SqlMetric(metric_name="count", expression="count(*)", table=table)
result_object = table.query(
{
"metrics": ["count"],
"is_timeseries": False,
"filter": [],
"from_dttm": datetime(2022, 1, 1),
"to_dttm": datetime(2023, 1, 1),
"granularity": "datetime_col",
}
)
""" >>> result_object.query
SELECT count(*) AS count
FROM
(SELECT '2021-12-31'::timestamp as datetime_col
UNION SELECT '2022-01-01'::timestamp
UNION SELECT '2022-03-10'::timestamp
UNION SELECT '2023-01-01'::timestamp
UNION SELECT '2023-03-10'::timestamp) AS virtual_table
WHERE datetime_col >= TO_TIMESTAMP('2022-01-01 00:00:00.000000', 'YYYY-MM-DD HH24:MI:SS.US')
AND datetime_col < TO_TIMESTAMP('2023-01-01 00:00:00.000000', 'YYYY-MM-DD HH24:MI:SS.US')
""" # noqa: E501
assert result_object.df.iloc[0]["count"] == 2
def test_none_operand_in_filter(login_as_admin, physical_dataset):
expected_results = [
{
"operator": FilterOperator.EQUALS,
"count": 10,
"sql_should_contain": "COL4 IS NULL",
},
{
"operator": FilterOperator.NOT_EQUALS,
"count": 0,
"sql_should_contain": "COL4 IS NOT NULL",
},
]
for expected in expected_results:
result = physical_dataset.query(
{
"metrics": ["count"],
"filter": [{"col": "col4", "val": None, "op": expected["operator"]}],
"is_timeseries": False,
}
)
assert result.df["count"][0] == expected["count"]
assert expected["sql_should_contain"] in result.query.upper()
with pytest.raises(QueryObjectValidationError): # noqa: PT012
for flt in [
FilterOperator.GREATER_THAN,
FilterOperator.LESS_THAN,
FilterOperator.GREATER_THAN_OR_EQUALS,
FilterOperator.LESS_THAN_OR_EQUALS,
FilterOperator.LIKE,
FilterOperator.ILIKE,
]:
physical_dataset.query(
{
"metrics": ["count"],
"filter": [{"col": "col4", "val": None, "op": flt.value}],
"is_timeseries": False,
}
)
@pytest.mark.usefixtures("app_context")
@pytest.mark.parametrize(
"table_name,sql,expected_cache_keys,has_extra_cache_keys",
[
(
"test_has_extra_cache_keys_table",
"""
SELECT
'{{ current_user_id() }}' as id,
'{{ current_username() }}' as username,
'{{ current_user_email() }}' as email,
'{{ current_user_roles()|tojson }}' as roles
""",
{1, "abc", "abc@test.com", '["role1", "role2"]'},
True,
),
(
"test_has_extra_cache_keys_table_with_set",
"""
{% set user_email = current_user_email() %}
SELECT
'{{ current_user_id() }}' as id,
'{{ current_username() }}' as username,
'{{ user_email }}' as email,
'{{ current_user_roles()|tojson }}' as roles
""",
{1, "abc", "abc@test.com", '["role1", "role2"]'},
True,
),
(
"test_has_extra_cache_keys_table_with_se_multiple",
"""
{% set user_conditional_id = current_user_email() and current_user_id() %}
SELECT
'{{ user_conditional_id }}' as conditional
""",
{1, "abc@test.com"},
True,
),
(
"test_has_extra_cache_keys_disabled_table",
"""
SELECT
'{{ current_user_id(False) }}' as id,
'{{ current_username(False) }}' as username,
'{{ current_user_email(False) }}' as email,
'{{ current_user_roles(False)|tojson }}' as roles
""",
[],
True,
),
("test_has_no_extra_cache_keys_table", "SELECT 'abc' as user", [], False),
],
)
@patch("superset.jinja_context.get_user_id", return_value=1)
@patch("superset.jinja_context.get_username", return_value="abc")
@patch("superset.jinja_context.get_user_email", return_value="abc@test.com")
@patch(
"superset.jinja_context.security_manager.get_user_roles",
return_value=[Role(name="role1"), Role(name="role2")],
)
def test_extra_cache_keys(
mock_get_user_roles,
mock_user_email,
mock_username,
mock_user_id,
table_name,
sql,
expected_cache_keys,
has_extra_cache_keys,
):
table = SqlaTable(
table_name=table_name,
sql=sql,
database=get_example_database(),
)
base_query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["id", "username", "email"],
"metrics": [],
"is_timeseries": False,
"filter": [],
}
query_obj = dict(**base_query_obj, extras={})
extra_cache_keys = table.get_extra_cache_keys(query_obj)
assert table.has_extra_cache_key_calls(query_obj) == has_extra_cache_keys
assert set(extra_cache_keys) == set(expected_cache_keys)
@pytest.mark.usefixtures("app_context")
@pytest.mark.parametrize(
"sql_expression,expected_cache_keys,has_extra_cache_keys",
[
("(user != '{{ current_username() }}')", ["abc"], True),
("(user != 'abc')", [], False),
],
)
@patch("superset.jinja_context.get_user_id", return_value=1)
@patch("superset.jinja_context.get_username", return_value="abc")
@patch("superset.jinja_context.get_user_email", return_value="abc@test.com")
@patch(
"superset.jinja_context.security_manager.get_user_roles",
return_value=[Role(name="role1"), Role(name="role2")],
)
def test_extra_cache_keys_in_sql_expression(
mock_get_user_roles,
mock_user_email,
mock_username,
mock_user_id,
sql_expression,
expected_cache_keys,
has_extra_cache_keys,
):
table = SqlaTable(
table_name="test_has_no_extra_cache_keys_table",
sql="SELECT 'abc' as user",
database=get_example_database(),
)
base_query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["id", "username", "email"],
"metrics": [],
"is_timeseries": False,
"filter": [],
}
query_obj = dict(**base_query_obj, extras={"where": sql_expression})
extra_cache_keys = table.get_extra_cache_keys(query_obj)
assert table.has_extra_cache_key_calls(query_obj) == has_extra_cache_keys
assert extra_cache_keys == expected_cache_keys
@pytest.mark.usefixtures("app_context")
@pytest.mark.parametrize(
"sql_expression,expected_cache_keys,has_extra_cache_keys,item_type",
[
("'{{ current_username() }}'", ["abc"], True, "columns"),
("(user != 'abc')", [], False, "columns"),
("{{ current_user_id() }}", [1], True, "metrics"),
("COUNT(*)", [], False, "metrics"),
],
)
@patch("superset.jinja_context.get_user_id", return_value=1)
@patch("superset.jinja_context.get_username", return_value="abc")
def test_extra_cache_keys_in_adhoc_metrics_and_columns(
mock_username: Mock,
mock_user_id: Mock,
sql_expression: str,
expected_cache_keys: list[str | None],
has_extra_cache_keys: bool,
item_type: Literal["columns", "metrics"],
):
table = SqlaTable(
table_name="test_has_no_extra_cache_keys_table",
sql="SELECT 'abc' as user",
database=get_example_database(),
)
base_query_obj: dict[str, Any] = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": [],
"metrics": [],
"columns": [],
"is_timeseries": False,
"filter": [],
}
items: dict[str, Any] = {
item_type: [
{
"label": None,
"expressionType": "SQL",
"sqlExpression": sql_expression,
}
],
}
query_obj = {**base_query_obj, **items}
extra_cache_keys = table.get_extra_cache_keys(cast(QueryObjectDict, query_obj))
assert (
table.has_extra_cache_key_calls(cast(QueryObjectDict, query_obj))
== has_extra_cache_keys
)
assert extra_cache_keys == expected_cache_keys
@pytest.mark.usefixtures("app_context")
@patch("superset.jinja_context.get_user_id", return_value=1)
@patch("superset.jinja_context.get_username", return_value="abc")
def test_extra_cache_keys_in_dataset_metrics_and_columns(
mock_username: Mock,
mock_user_id: Mock,
):
table = SqlaTable(
table_name="test_has_no_extra_cache_keys_table",
sql="SELECT 'abc' as user",
database=get_example_database(),
columns=[
TableColumn(column_name="user", type="VARCHAR(255)"),
TableColumn(
column_name="username",
type="VARCHAR(255)",
expression="{{ current_username() }}",
),
],
metrics=[
SqlMetric(
metric_name="variable_profit",
expression="SUM(price) * {{ url_param('multiplier') }}",
),
],
)
query_obj: dict[str, Any] = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": [],
"columns": ["username"],
"metrics": ["variable_profit"],
"is_timeseries": False,
"filter": [],
}
extra_cache_keys = table.get_extra_cache_keys(cast(QueryObjectDict, query_obj))
assert table.has_extra_cache_key_calls(cast(QueryObjectDict, query_obj)) is True
assert set(extra_cache_keys) == {"abc", None}
@pytest.mark.usefixtures("app_context")
@pytest.mark.parametrize(
"row,dimension,result",
[
(pd.Series({"foo": "abc"}), "foo", "abc"),
(pd.Series({"bar": True}), "bar", True),
(pd.Series({"baz": 123}), "baz", 123),
(pd.Series({"baz": np.int16(123)}), "baz", 123),
(pd.Series({"baz": np.uint32(123)}), "baz", 123),
(pd.Series({"baz": np.int64(123)}), "baz", 123),
(pd.Series({"qux": 123.456}), "qux", 123.456),
(pd.Series({"qux": np.float32(123.456)}), "qux", 123.45600128173828),
(pd.Series({"qux": np.float64(123.456)}), "qux", 123.456),
(pd.Series({"quux": "2021-01-01"}), "quux", "2021-01-01"),
(
pd.Series({"quuz": "2021-01-01T00:00:00"}),
"quuz",
text("TIME_PARSE('2021-01-01T00:00:00')"),
),
],
)
def test__normalize_prequery_result_type(
mocker: MockerFixture,
row: pd.Series,
dimension: str,
result: Any,
) -> None:
def _convert_dttm(
target_type: str, dttm: datetime, db_extra: Optional[dict[str, Any]] = None
) -> Optional[str]:
if target_type.upper() == "TIMESTAMP":
return f"""TIME_PARSE('{dttm.isoformat(timespec="seconds")}')"""
return None
table = SqlaTable(table_name="foobar", database=get_example_database())
mocker.patch.object(table.db_engine_spec, "convert_dttm", new=_convert_dttm)
columns_by_name = {
"foo": TableColumn(
column_name="foo",
is_dttm=False,
table=table,
type="STRING",
),
"bar": TableColumn(
column_name="bar",
is_dttm=False,
table=table,
type="BOOLEAN",
),
"baz": TableColumn(
column_name="baz",
is_dttm=False,
table=table,
type="INTEGER",
),
"qux": TableColumn(
column_name="qux",
is_dttm=False,
table=table,
type="FLOAT",
),
"quux": TableColumn(
column_name="quuz",
is_dttm=True,
table=table,
type="STRING",
),
"quuz": TableColumn(
column_name="quux",
is_dttm=True,
table=table,
type="TIMESTAMP",
),
}
normalized = table._normalize_prequery_result_type(
row,
dimension,
columns_by_name,
)
assert isinstance(normalized, type(result))
if isinstance(normalized, TextClause):
assert str(normalized) == str(result)
else:
assert normalized == result
@pytest.mark.usefixtures("app_context")
def test__temporal_range_operator_in_adhoc_filter(physical_dataset):
result = physical_dataset.query(
{
"columns": ["col1", "col2"],
"filter": [
{
"col": "col5",
"val": "2000-01-05 : 2000-01-06",
"op": FilterOperator.TEMPORAL_RANGE,
},
{
"col": "col6",
"val": "2002-05-11 : 2002-05-12",
"op": FilterOperator.TEMPORAL_RANGE,
},
],
"is_timeseries": False,
}
)
df = pd.DataFrame(index=[0], data={"col1": 4, "col2": "e"})
assert df.equals(result.df)
def test_generic_metric_filtering_without_chart_flag(login_as_admin):
"""
Test that filters on metrics work without chart-specific flags.
This ensures metric filtering is generic and works for any chart type.
"""
from superset import db
from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
from superset.utils.database import get_example_database
database = get_example_database()
table = SqlaTable(
table_name="test_metric_filter",
database=database,
)
col = TableColumn(
column_name="name",
type="VARCHAR(255)",
table=table,
)
table.columns = [col]
metric = SqlMetric(
metric_name="count",
expression="COUNT(*)",
table=table,
)
table.metrics = [metric]
db.session.add(table)
db.session.commit()
try:
query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["name"],
"metrics": ["count"],
"filter": [
{
"col": "count",
"op": ">",
"val": 0,
}
],
"is_timeseries": False,
"extras": {},
}
sqla_query = table.get_sqla_query(**query_obj)
sql = str(
sqla_query.sqla_query.compile(compile_kwargs={"literal_binds": True})
).lower()
assert "having" in sql, "Metric filter should use HAVING clause. SQL: " + sql
finally:
db.session.delete(table)
db.session.commit()
def test_column_ordering_without_chart_flag(login_as_admin):
"""
Test that column_order works without chart-specific flags.
This ensures column ordering is generic and works for any chart type.
"""
from unittest.mock import patch
from superset import db
from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
from superset.utils.database import get_example_database
database = get_example_database()
table = SqlaTable(
table_name="test_column_order",
database=database,
)
col_a = TableColumn(column_name="col_a", type="VARCHAR(255)", table=table)
col_b = TableColumn(column_name="col_b", type="VARCHAR(255)", table=table)
table.columns = [col_a, col_b]
metric_x = SqlMetric(metric_name="metric_x", expression="COUNT(*)", table=table)
metric_y = SqlMetric(metric_name="metric_y", expression="SUM(val)", table=table)
table.metrics = [metric_x, metric_y]
db.session.add(table)
db.session.commit()
try:
mock_df = pd.DataFrame(
{
"col_a": [1, 2],
"col_b": [3, 4],
"metric_x": [10, 20],
"metric_y": [100, 200],
}
)
def mock_get_df(sql, catalog=None, schema=None, mutator=None):
"""Mock get_df that calls the mutator function if provided."""
df = mock_df.copy()
if mutator:
df = mutator(df)
return df
with patch.object(database, "get_df", side_effect=mock_get_df):
query_obj = {
"granularity": None,
"from_dttm": None,
"to_dttm": None,
"groupby": ["col_a", "col_b"],
"metrics": ["metric_x", "metric_y"],
"filter": [],
"is_timeseries": False,
"extras": {"column_order": ["metric_y", "col_b", "metric_x", "col_a"]},
}
result = table.query(query_obj)
expected_order = ["metric_y", "col_b", "metric_x", "col_a"]
assert list(result.df.columns) == expected_order, (
f"Expected {expected_order}, got {list(result.df.columns)}"
)
finally:
db.session.delete(table)
db.session.commit()