forked from aws/aws-sdk-pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_athena.py
More file actions
1769 lines (1552 loc) · 62.3 KB
/
Copy pathtest_athena.py
File metadata and controls
1769 lines (1552 loc) · 62.3 KB
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
import datetime
import logging
import string
from typing import Any
from unittest.mock import patch
import boto3
import botocore
import numpy as np
import pytest
from pandas import DataFrame as PandasDataFrame
import awswrangler as wr
import awswrangler.pandas as pd
from .._utils import (
assert_pandas_equals,
ensure_athena_ctas_table,
ensure_athena_query_metadata,
ensure_data_types,
ensure_data_types_category,
get_df,
get_df_category,
get_df_list,
get_df_txt,
get_time_str_with_random_suffix,
pandas_equals,
)
logging.getLogger("awswrangler").setLevel(logging.DEBUG)
pytestmark = pytest.mark.distributed
def test_athena_ctas(path, path2, path3, glue_table, glue_table2, glue_database, glue_ctas_database, kms_key):
df = get_df_list()
columns_types, partitions_types = wr.catalog.extract_athena_types(df=df, partition_cols=["par0", "par1"])
assert len(columns_types) == 17
assert len(partitions_types) == 2
with pytest.raises(wr.exceptions.InvalidArgumentValue):
wr.catalog.extract_athena_types(df=df, file_format="avro")
wr.s3.to_parquet(
df=get_df_list(),
path=path,
index=True,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
dirs = wr.s3.list_directories(path=path)
for d in dirs:
assert d.startswith(f"{path}par0=")
df = wr.s3.read_parquet_table(table=glue_table, database=glue_database)
assert len(df.index) == 3
ensure_data_types(df=df, has_list=True)
df = wr.athena.read_sql_table(
table=glue_table,
database=glue_database,
ctas_approach=True,
encryption="SSE_KMS",
kms_key=kms_key,
s3_output=path2,
keep_files=False,
)
assert len(df.index) == 3
ensure_data_types(df=df, has_list=True)
ensure_athena_query_metadata(df=df, ctas_approach=True, encrypted=True)
final_destination = f"{path3}{glue_table2}/"
# keep_files=False
wr.s3.delete_objects(path=path3)
dfs = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table}",
database=glue_database,
ctas_approach=True,
chunksize=1,
keep_files=False,
ctas_parameters=wr.typing.AthenaCTASSettings(
temp_table_name=glue_table2,
),
s3_output=path3,
)
assert wr.catalog.does_table_exist(database=glue_database, table=glue_table2) is False
assert len(wr.s3.list_objects(path=path3)) > 2
assert len(wr.s3.list_objects(path=final_destination)) > 0
for df in dfs:
ensure_data_types(df=df, has_list=True)
ensure_athena_query_metadata(df=df, ctas_approach=True, encrypted=False)
assert len(wr.s3.list_objects(path=path3)) == 0
# keep_files=True
wr.s3.delete_objects(path=path3)
dfs = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table}",
database=glue_database,
ctas_approach=True,
chunksize=2,
keep_files=True,
ctas_parameters=wr.typing.AthenaCTASSettings(
temp_table_name=glue_table2,
),
s3_output=path3,
)
assert wr.catalog.does_table_exist(database=glue_database, table=glue_table2) is False
assert len(wr.s3.list_objects(path=path3)) > 2
assert len(wr.s3.list_objects(path=final_destination)) > 0
for df in dfs:
ensure_data_types(df=df, has_list=True)
ensure_athena_query_metadata(df=df, ctas_approach=True, encrypted=False)
assert len(wr.s3.list_objects(path=path3)) > 2
# ctas_database_name
wr.s3.delete_objects(path=path3)
dfs = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table}",
database=glue_database,
ctas_approach=True,
chunksize=1,
keep_files=False,
ctas_parameters=wr.typing.AthenaCTASSettings(
database=glue_ctas_database,
temp_table_name=glue_table2,
),
s3_output=path3,
)
assert wr.catalog.does_table_exist(database=glue_ctas_database, table=glue_table2) is False
assert len(wr.s3.list_objects(path=path3)) > 2
assert len(wr.s3.list_objects(path=final_destination)) > 0
for df in dfs:
ensure_data_types(df=df, has_list=True)
ensure_athena_query_metadata(df=df, ctas_approach=True, encrypted=False)
assert len(wr.s3.list_objects(path=path3)) == 0
def test_athena_read_sql_ctas_bucketing(path, path2, glue_table, glue_table2, glue_database, glue_ctas_database):
df = pd.DataFrame({"c0": [0, 1], "c1": ["foo", "bar"]})
wr.s3.to_parquet(
df=df,
path=path,
dataset=True,
database=glue_database,
table=glue_table,
)
df_ctas = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table}",
ctas_approach=True,
database=glue_database,
ctas_parameters=wr.typing.AthenaCTASSettings(
database=glue_ctas_database,
temp_table_name=glue_table2,
bucketing_info=(["c0"], 1),
),
s3_output=path2,
pyarrow_additional_kwargs={"ignore_metadata": True},
)
df_no_ctas = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table}",
ctas_approach=False,
database=glue_database,
s3_output=path2,
pyarrow_additional_kwargs={"ignore_metadata": True},
)
assert df_ctas.equals(df_no_ctas)
def test_athena_create_ctas(path, glue_table, glue_table2, glue_database, glue_ctas_database, kms_key):
boto3_session = boto3.DEFAULT_SESSION
wr.s3.to_parquet(
df=get_df_list(),
path=path,
index=False,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
# Select *
ctas_query_info = wr.athena.create_ctas_table(
sql=f"select * from {glue_table}",
database=glue_database,
encryption="SSE_KMS",
kms_key=kms_key,
wait=False,
)
ensure_athena_ctas_table(ctas_query_info=ctas_query_info, boto3_session=boto3_session)
# Schema only (i.e. WITH NO DATA)
ctas_query_info = wr.athena.create_ctas_table(
sql=f"select * from {glue_table}",
database=glue_database,
ctas_table=glue_table2,
schema_only=True,
wait=True,
)
ensure_athena_ctas_table(ctas_query_info=ctas_query_info, boto3_session=boto3_session)
# Convert to new data storage and compression
ctas_query_info = wr.athena.create_ctas_table(
sql=f"select string, bool from {glue_table}",
database=glue_database,
storage_format="avro",
write_compression="snappy",
wait=False,
)
ensure_athena_ctas_table(ctas_query_info=ctas_query_info, boto3_session=boto3_session)
# Partition and save to CTAS database
ctas_query_info = wr.athena.create_ctas_table(
sql=f"select * from {glue_table}",
database=glue_database,
ctas_database=glue_ctas_database,
partitioning_info=["par0", "par1"],
wait=True,
)
ensure_athena_ctas_table(ctas_query_info=ctas_query_info, boto3_session=boto3_session)
def test_athena_create_ctas_with_named_params(path, glue_table, glue_database, glue_ctas_database):
wr.s3.to_parquet(
df=get_df_list(),
path=path,
index=False,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
)
wr.athena.create_ctas_table(
sql=f"SELECT * FROM {glue_table} WHERE par1 = :par1",
database=glue_database,
ctas_database=glue_ctas_database,
params={"par1": "b"},
paramstyle="named",
wait=True,
)
def test_athena_create_ctas_with_qmark_params(path, glue_table, glue_database, glue_ctas_database):
wr.s3.to_parquet(
df=get_df_list(),
path=path,
index=False,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
)
wr.athena.create_ctas_table(
sql=f"SELECT * FROM {glue_table} WHERE par1 = ?",
database=glue_database,
ctas_database=glue_ctas_database,
params=["b"],
paramstyle="qmark",
wait=True,
)
def test_athena_create_ctas_with_execution_params_deprecation_warning(
path, glue_table, glue_database, glue_ctas_database
):
wr.s3.to_parquet(
df=get_df_list(),
path=path,
index=False,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
)
with pytest.raises(DeprecationWarning):
wr.athena.create_ctas_table(
sql=f"SELECT * FROM {glue_table} WHERE par1 = ?",
database=glue_database,
ctas_database=glue_ctas_database,
execution_params=["b"],
wait=True,
)
def test_athena_create_ctas_with_params_and_execution_params_error(path, glue_table, glue_database, glue_ctas_database):
wr.s3.to_parquet(
df=get_df_list(),
path=path,
index=False,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
)
with pytest.raises(wr.exceptions.InvalidArgumentCombination):
wr.athena.create_ctas_table(
sql=f"SELECT * FROM {glue_table} WHERE par1 = ?",
database=glue_database,
ctas_database=glue_ctas_database,
execution_params=["b"],
params=["b"],
paramstyle="qmark",
wait=True,
)
def test_athena(path, glue_database, glue_table, kms_key, workgroup0, workgroup1):
wr.s3.to_parquet(
df=get_df(),
path=path,
index=True,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
dfs = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table}",
database=glue_database,
ctas_approach=False,
chunksize=1,
encryption="SSE_KMS",
kms_key=kms_key,
workgroup=workgroup0,
keep_files=False,
)
for df2 in dfs:
ensure_data_types(df=df2)
ensure_athena_query_metadata(df=df2, ctas_approach=False, encrypted=False)
df = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table}",
database=glue_database,
ctas_approach=False,
workgroup=workgroup1,
keep_files=False,
)
assert len(df.index) == 3
ensure_data_types(df=df)
ensure_athena_query_metadata(df=df, ctas_approach=False, encrypted=False)
wr.athena.repair_table(table=glue_table, database=glue_database)
assert len(wr.athena.describe_table(database=glue_database, table=glue_table).index) > 0
assert (
wr.catalog.table(database=glue_database, table=glue_table).to_dict()
== wr.athena.describe_table(database=glue_database, table=glue_table).to_dict()
)
df = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table} WHERE iint8 = :iint8_value",
database=glue_database,
ctas_approach=False,
workgroup=workgroup1,
keep_files=False,
params={"iint8_value": 1},
)
assert len(df.index) == 1
ensure_athena_query_metadata(df=df, ctas_approach=False, encrypted=False)
query = wr.athena.show_create_table(database=glue_database, table=glue_table)
assert (
query.split("LOCATION")[0] == f"CREATE EXTERNAL TABLE `{glue_table}`"
f"( `iint8` tinyint,"
f" `iint16` smallint,"
f" `iint32` int,"
f" `iint64` bigint,"
f" `float` float,"
f" `ddouble` double,"
f" `decimal` decimal(3,2),"
f" `string_object` string,"
f" `string` string,"
f" `date` date,"
f" `timestamp` timestamp,"
f" `bool` boolean,"
f" `binary` binary,"
f" `category` double,"
f" `__index_level_0__` bigint) "
f"PARTITIONED BY ( `par0` bigint, `par1` string) "
f"ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe' "
f"STORED AS INPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat' "
f"OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat' "
)
def test_athena_orc(path, glue_database, glue_table):
df = pd.DataFrame({"c0": [1, 2, 3], "c1": ["foo", "bar", "foo"], "par": ["a", "b", "c"]})
df["c0"] = df["c0"].astype("Int64")
df["c1"] = df["c1"].astype("string")
df["par"] = df["par"].astype("string")
wr.s3.to_orc(
df=df,
path=path,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par"],
)
df_out = wr.athena.read_sql_table(
table=glue_table,
database=glue_database,
ctas_approach=False,
keep_files=False,
)
df_out = df_out.sort_values(by="c0", ascending=True).reset_index(drop=True)
assert_pandas_equals(df, df_out)
@pytest.mark.parametrize(
"ctas_approach,unload_approach",
[
pytest.param(False, False, id="regular"),
pytest.param(True, False, id="ctas"),
pytest.param(False, True, id="unload"),
],
)
@pytest.mark.parametrize(
"col_name,col_value", [("string", "Washington"), ("iint32", "1"), ("date", "DATE '2020-01-01'")]
)
def test_athena_paramstyle_qmark_parameters(
path: str,
path2: str,
glue_database: str,
glue_table: str,
workgroup0: str,
ctas_approach: bool,
unload_approach: bool,
col_name: str,
col_value: Any,
) -> None:
wr.s3.to_parquet(
df=get_df(),
path=path,
index=False,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
df_out = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table} WHERE {col_name} = ?",
database=glue_database,
ctas_approach=ctas_approach,
unload_approach=unload_approach,
workgroup=workgroup0,
params=[col_value],
paramstyle="qmark",
keep_files=False,
s3_output=path2,
)
ensure_data_types(df=df_out)
ensure_athena_query_metadata(df=df_out, ctas_approach=ctas_approach, encrypted=False)
assert len(df_out) == 1
@pytest.mark.parametrize(
"ctas_approach,unload_approach",
[
pytest.param(False, False, id="regular"),
pytest.param(True, False, id="ctas"),
pytest.param(False, True, id="unload"),
],
)
def test_athena_paramstyle_qmark_skip_caching(
path: str,
path2: str,
glue_database: str,
glue_table: str,
workgroup0: str,
ctas_approach: bool,
unload_approach: bool,
) -> None:
wr.s3.to_parquet(
df=get_df(),
path=path,
index=False,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
df_out = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table} WHERE string = ?",
database=glue_database,
ctas_approach=ctas_approach,
unload_approach=unload_approach,
workgroup=workgroup0,
params=["Washington"],
paramstyle="qmark",
keep_files=False,
s3_output=path2,
athena_cache_settings={"max_cache_seconds": 300},
)
assert len(df_out) == 1 and df_out.iloc[0]["string"] == "Washington"
df_out = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table} WHERE string = ?",
database=glue_database,
ctas_approach=ctas_approach,
unload_approach=unload_approach,
workgroup=workgroup0,
params=["Seattle"],
paramstyle="qmark",
keep_files=False,
s3_output=path2,
athena_cache_settings={"max_cache_seconds": 300},
)
assert len(df_out) == 1 and df_out.iloc[0]["string"] == "Seattle"
def test_read_sql_query_parameter_formatting_respects_prefixes(path, glue_database, glue_table, workgroup0):
wr.s3.to_parquet(
df=get_df(),
path=path,
index=True,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
df = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table} WHERE string = :string OR string_object = :string_object",
database=glue_database,
ctas_approach=False,
workgroup=workgroup0,
keep_files=False,
params={"string": "Seattle", "string_object": "boo"},
)
assert len(df) == 2
@pytest.mark.parametrize(
"col_name,col_value",
[("string", "Seattle"), ("date", datetime.date(2020, 1, 1)), ("bool", True), ("category", 1.0)],
)
def test_read_sql_query_parameter_formatting(path, glue_database, glue_table, workgroup0, col_name, col_value):
wr.s3.to_parquet(
df=get_df(),
path=path,
index=True,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
df = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table} WHERE {col_name} = :value",
database=glue_database,
ctas_approach=False,
workgroup=workgroup0,
keep_files=False,
params={"value": col_value},
)
assert len(df.index) == 1
@pytest.mark.parametrize("col_name", [("string"), ("date"), ("bool"), ("category")])
def test_read_sql_query_parameter_formatting_null(path, glue_database, glue_table, workgroup0, col_name):
wr.s3.to_parquet(
df=get_df(),
path=path,
index=True,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
partition_cols=["par0", "par1"],
)
df = wr.athena.read_sql_query(
sql=f"SELECT * FROM {glue_table} WHERE {col_name} IS :value",
database=glue_database,
ctas_approach=False,
workgroup=workgroup0,
keep_files=False,
params={"value": None},
)
assert len(df.index) == 1
@pytest.mark.xfail(raises=botocore.exceptions.ClientError, reason="QueryId not found.")
def test_athena_query_cancelled(glue_database):
query_execution_id = wr.athena.start_query_execution(
sql="SELECT " + "rand(), " * 10000 + "rand()", database=glue_database
)
wr.athena.stop_query_execution(query_execution_id=query_execution_id)
with pytest.raises(wr.exceptions.QueryCancelled):
assert wr.athena.wait_query(query_execution_id=query_execution_id)
def test_athena_query_failed(glue_database):
query_execution_id = wr.athena.start_query_execution(sql="SELECT random(-1)", database=glue_database)
with pytest.raises(wr.exceptions.QueryFailed):
assert wr.athena.wait_query(query_execution_id=query_execution_id)
def test_athena_read_list(glue_database):
df = wr.athena.read_sql_query(sql="SELECT ARRAY[1, 2, 3] AS col0", database=glue_database, ctas_approach=False)
assert len(df) == 1
assert len(df.index) == 1
assert len(df.columns) == 1
assert df["col0"].iloc[0] == "[1, 2, 3]"
def test_athena_read_json(glue_database):
sql = """
WITH dataset AS (
SELECT
CAST('HELLO ATHENA' AS JSON) AS some_str,
CAST(12345 AS JSON) AS some_int,
CAST(MAP(ARRAY['a', 'b'], ARRAY[1,2]) AS JSON) AS some_map
)
SELECT * FROM dataset
"""
df = wr.athena.read_sql_query(sql=sql, database=glue_database, ctas_approach=False)
assert len(df) == 1
assert len(df.index) == 1
assert len(df.columns) == 3
assert df["some_str"].iloc[0] == '"HELLO ATHENA"'
assert df["some_int"].iloc[0] == "12345"
assert df["some_map"].iloc[0] == '{"a":1,"b":2}'
def test_athena_read_json_extract(glue_database):
sql = """
WITH dataset AS (
SELECT '{"name": "Susan Smith",
"org": "engineering",
"projects": [{"name":"project1", "completed":false},
{"name":"project2", "completed":true}]}'
AS myblob
)
SELECT
json_extract(myblob, '$.name') AS name,
json_extract(myblob, '$.projects') AS projects
FROM dataset
"""
df = wr.athena.read_sql_query(sql=sql, database=glue_database, ctas_approach=False)
assert len(df) == 1
assert len(df.index) == 1
assert len(df.columns) == 2
assert df["name"].iloc[0] == '"Susan Smith"'
assert df["projects"].iloc[0] == '[{"name":"project1","completed":false},{"name":"project2","completed":true}]'
def test_sanitize_dataframe_column_names():
with pytest.warns(UserWarning, match=r"Duplicate*"):
test_df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
test_df.columns = ["a", "a"]
assert wr.catalog.sanitize_dataframe_columns_names(df=pd.DataFrame({"A": [1, 2], "a": [3, 4]})).equals(test_df)
assert wr.catalog.sanitize_dataframe_columns_names(
df=pd.DataFrame({"A": [1, 2], "a": [3, 4]}), handle_duplicate_columns="drop"
).equals(pd.DataFrame({"a": [1, 2]}))
assert wr.catalog.sanitize_dataframe_columns_names(
df=pd.DataFrame({"A": [1, 2], "a": [3, 4], "a_1": [5, 6]}), handle_duplicate_columns="rename"
).equals(pd.DataFrame({"a": [1, 2], "a_1": [3, 4], "a_1_1": [5, 6]}))
def test_sanitize_names():
assert wr.catalog.sanitize_column_name("CamelCase") == "camelcase"
assert wr.catalog.sanitize_column_name("CamelCase2") == "camelcase2"
assert wr.catalog.sanitize_column_name("Camel_Case3") == "camel_case3"
assert wr.catalog.sanitize_column_name("Cámël_Casë4仮") == "camel_case4_"
assert wr.catalog.sanitize_column_name("Camel__Case5") == "camel__case5"
assert wr.catalog.sanitize_column_name("Camel{}Case6") == "camel_case6"
assert wr.catalog.sanitize_column_name("Camel.Case7") == "camel_case7"
assert wr.catalog.sanitize_column_name("xyz_cd") == "xyz_cd"
assert wr.catalog.sanitize_column_name("xyz_Cd") == "xyz_cd"
assert wr.catalog.sanitize_table_name("CamelCase") == "camelcase"
assert wr.catalog.sanitize_table_name("CamelCase2") == "camelcase2"
assert wr.catalog.sanitize_table_name("Camel_Case3") == "camel_case3"
assert wr.catalog.sanitize_table_name("Cámël_Casë4仮") == "camel_case4_"
assert wr.catalog.sanitize_table_name("Camel__Case5") == "camel__case5"
assert wr.catalog.sanitize_table_name("Camel{}Case6") == "camel_case6"
assert wr.catalog.sanitize_table_name("Camel.Case7") == "camel_case7"
assert wr.catalog.sanitize_table_name("xyz_cd") == "xyz_cd"
assert wr.catalog.sanitize_table_name("xyz_Cd") == "xyz_cd"
def test_athena_ctas_empty(glue_database):
sql = """
WITH dataset AS (
SELECT 0 AS id
)
SELECT id
FROM dataset
WHERE id != 0
"""
df1 = wr.athena.read_sql_query(sql=sql, database=glue_database)
assert df1.empty is True
ensure_athena_query_metadata(df=df1, ctas_approach=True, encrypted=False)
assert len(list(wr.athena.read_sql_query(sql=sql, database=glue_database, chunksize=1))) == 1
def test_athena_struct_simple(path, glue_database):
sql = "SELECT CAST(ROW(1, 'foo') AS ROW(id BIGINT, value VARCHAR)) AS col0"
# Regular approach
df = wr.athena.read_sql_query(sql=sql, database=glue_database, ctas_approach=False)
assert len(df) == 1
assert len(df.index) == 1
assert len(df.columns) == 1
assert df["col0"].iloc[0] == "{id=1, value=foo}"
# CTAS and UNLOAD
with pytest.raises(wr.exceptions.InvalidArgumentCombination):
wr.athena.read_sql_query(sql=sql, database=glue_database, ctas_approach=True, unload_approach=True)
# CTAS approach
df_ctas = wr.athena.read_sql_query(sql=sql, database=glue_database, ctas_approach=True)
assert len(df_ctas.index) == 1
assert len(df_ctas.columns) == 1
assert df_ctas["col0"].iloc[0]["id"] == 1
assert df_ctas["col0"].iloc[0]["value"] == "foo"
# UNLOAD approach
df_unload = wr.athena.read_sql_query(
sql=sql, database=glue_database, ctas_approach=False, unload_approach=True, s3_output=path
)
assert df_unload.equals(df_ctas)
def test_athena_struct_nested(path, glue_database):
sql = (
"SELECT CAST("
" ROW(1, ROW(2, ROW(3, '4'))) AS"
" ROW(field0 BIGINT, field1 ROW(field2 BIGINT, field3 ROW(field4 BIGINT, field5 VARCHAR)))"
") AS col0"
)
# CTAS approach
df_ctas = wr.athena.read_sql_query(sql=sql, database=glue_database, ctas_approach=True)
assert len(df_ctas.index) == 1
assert len(df_ctas.columns) == 1
assert df_ctas["col0"].iloc[0]["field0"] == 1
assert df_ctas["col0"].iloc[0]["field1"]["field2"] == 2
assert df_ctas["col0"].iloc[0]["field1"]["field3"]["field4"] == 3
assert df_ctas["col0"].iloc[0]["field1"]["field3"]["field5"] == "4"
# UNLOAD approach
df_unload = wr.athena.read_sql_query(
sql=sql, database=glue_database, ctas_approach=False, unload_approach=True, s3_output=path
)
assert df_unload.equals(df_ctas)
def test_athena_time_zone(glue_database):
sql = "SELECT current_timestamp AS value, typeof(current_timestamp) AS type"
df = wr.athena.read_sql_query(sql=sql, database=glue_database, ctas_approach=False)
assert len(df.index) == 1
assert len(df.columns) == 2
assert df["type"][0] == "timestamp(3) with time zone"
assert df["value"][0].year == datetime.datetime.utcnow().year
@pytest.mark.parametrize("dtype_backend", ["numpy_nullable", "pyarrow"])
def test_athena_time_type(glue_database: str, dtype_backend: str) -> None:
df = wr.athena.read_sql_query(
"SELECT time '13:24:11' as col", glue_database, ctas_approach=False, dtype_backend=dtype_backend
)
if dtype_backend == "pyarrow":
assert df["col"].iloc[0] == datetime.time(13, 24, 11)
else:
assert df["col"].iloc[0] == "13:24:11"
@pytest.mark.parametrize(
"ctas_approach",
[
pytest.param(False),
pytest.param(
True,
marks=pytest.mark.xfail(
raises=NotImplementedError, reason="Unable to create pandas categorical from pyarrow table"
),
),
],
)
def test_category(path: str, glue_table: str, glue_database: str, ctas_approach: bool) -> None:
df = get_df_category()
wr.s3.to_parquet(
df=df,
path=path,
dataset=True,
database=glue_database,
table=glue_table,
mode="overwrite",
partition_cols=["par0", "par1"],
)
df2 = wr.athena.read_sql_query(
f"SELECT * FROM {glue_table}", database=glue_database, categories=list(df.columns), ctas_approach=ctas_approach
)
ensure_data_types_category(df2)
@pytest.mark.parametrize(
"ctas_approach",
[
pytest.param(False),
pytest.param(
True,
marks=pytest.mark.xfail(
raises=NotImplementedError, reason="Unable to create pandas categorical from pyarrow table"
),
),
],
)
def test_category_chunked(path: str, glue_table: str, glue_database: str, ctas_approach: bool) -> None:
df = get_df_category()
wr.s3.to_parquet(
df=df,
path=path,
dataset=True,
database=glue_database,
table=glue_table,
mode="overwrite",
partition_cols=["par0", "par1"],
)
dfs = wr.athena.read_sql_query(
f"SELECT * FROM {glue_table}",
database=glue_database,
categories=list(df.columns),
ctas_approach=ctas_approach,
chunksize=1,
)
for df2 in dfs:
ensure_data_types_category(df2)
@pytest.mark.parametrize("workgroup", [None, 0, 1, 2, 3])
@pytest.mark.parametrize("encryption", [None, "SSE_S3", "SSE_KMS"])
@pytest.mark.parametrize("ctas_approach", [False, True])
def test_athena_encryption(
path,
path2,
glue_database,
glue_table,
glue_table2,
kms_key,
ctas_approach,
encryption,
workgroup,
workgroup0,
workgroup1,
workgroup2,
workgroup3,
):
kms_key = None if (encryption == "SSE_S3") or (encryption is None) else kms_key
if workgroup == 0:
workgroup = workgroup0
elif workgroup == 1:
workgroup = workgroup1
elif workgroup == 2:
workgroup = workgroup2
elif workgroup == 3:
workgroup = workgroup3
df = pd.DataFrame({"a": [1, 2], "b": ["foo", "boo"]})
wr.s3.to_parquet(
df=df,
path=path,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
s3_additional_kwargs=None,
)
df2 = wr.athena.read_sql_table(
table=glue_table,
ctas_approach=ctas_approach,
database=glue_database,
encryption=encryption,
workgroup=workgroup,
kms_key=kms_key,
keep_files=True,
ctas_parameters=wr.typing.AthenaCTASSettings(
temp_table_name=glue_table2,
),
s3_output=path2,
)
assert wr.catalog.does_table_exist(database=glue_database, table=glue_table2) is False
assert df2.shape == (2, 2)
def test_athena_nested(path, glue_database, glue_table):
df = pd.DataFrame(
{
"c0": [[1, 2, 3], [4, 5, 6]],
"c1": [[[1, 2], [3, 4]], [[5, 6], [7, 8]]],
"c2": [[["a", "b"], ["c", "d"]], [["e", "f"], ["g", "h"]]],
"c3": [[], [[[[[[[[1]]]]]]]]],
"c4": [{"a": 1}, {"a": 1}],
"c5": [{"a": {"b": {"c": [1, 2]}}}, {"a": {"b": {"c": [3, 4]}}}],
}
)
wr.s3.to_parquet(
df=df,
path=path,
index=False,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
)
df2 = wr.athena.read_sql_query(sql=f"SELECT c0, c1, c2, c4 FROM {glue_table}", database=glue_database)
assert len(df2.index) == 2
assert len(df2.columns) == 4
def test_athena_get_query_column_types(path, glue_database, glue_table):
df = get_df()
wr.s3.to_parquet(
df=df,
path=path,
index=False,
use_threads=True,
dataset=True,
mode="overwrite",
database=glue_database,
table=glue_table,
)
query_execution_id = wr.athena.start_query_execution(sql=f"SELECT * FROM {glue_table}", database=glue_database)
wr.athena.wait_query(query_execution_id=query_execution_id)
column_types = wr.athena.get_query_columns_types(query_execution_id=query_execution_id)
assert len(column_types) == len(df.columns)
assert set(column_types.keys()) == set(df.columns)
def test_athena_undefined_column(glue_database):
with pytest.raises(wr.exceptions.InvalidArgumentValue):
wr.athena.read_sql_query("SELECT 1", glue_database)
with pytest.raises(wr.exceptions.InvalidArgumentValue):
wr.athena.read_sql_query("SELECT NULL AS my_null", glue_database)
def test_glue_database():
# Round 1 - Create Database
glue_database_name = f"database_{get_time_str_with_random_suffix()}"
wr.catalog.create_database(name=glue_database_name, description="Database Description")
databases = wr.catalog.get_databases()
test_database_name = ""
test_database_description = ""
for database in databases:
if database["Name"] == glue_database_name:
test_database_name = database["Name"]
test_database_description = database["Description"]
assert test_database_name == glue_database_name
assert test_database_description == "Database Description"
# Round 2 - Delete Database
wr.catalog.delete_database(name=glue_database_name)
databases = wr.catalog.get_databases()
test_database_name = ""
test_database_description = ""
for database in databases:
if database["Name"] == glue_database_name:
test_database_name = database["Name"]
test_database_description = database["Description"]
assert test_database_name == ""
assert test_database_description == ""
def test_read_sql_query_wo_results(path, glue_database, glue_table):
wr.catalog.create_parquet_table(database=glue_database, table=glue_table, path=path, columns_types={"c0": "int"})
sql = f"ALTER TABLE {glue_database}.{glue_table} SET LOCATION '{path}dir/'"
df = wr.athena.read_sql_query(sql, database=glue_database, ctas_approach=False)
assert df.empty
ensure_athena_query_metadata(df=df, ctas_approach=False, encrypted=False)
@pytest.mark.parametrize("ctas_approach", [False, True])
def test_read_sql_query_wo_results_chunked(path, glue_database, glue_table, ctas_approach):
wr.catalog.create_parquet_table(database=glue_database, table=glue_table, path=path, columns_types={"c0": "int"})
sql = f"SELECT * FROM {glue_database}.{glue_table}"
counter = 0
for df in wr.athena.read_sql_query(sql, database=glue_database, ctas_approach=ctas_approach, chunksize=100):
assert df.empty
counter += 1
assert counter == 1
@pytest.mark.xfail(raises=botocore.exceptions.ClientError)