-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathtest_data_source_api.py
More file actions
1911 lines (1668 loc) · 70.5 KB
/
test_data_source_api.py
File metadata and controls
1911 lines (1668 loc) · 70.5 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
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import decimal
import functools
import logging
import math
import multiprocessing
import threading
import os
import subprocess
import tempfile
import datetime
import queue
from io import BytesIO
from textwrap import dedent
from unittest import mock
from unittest.mock import patch, MagicMock, PropertyMock
from concurrent.futures import ThreadPoolExecutor
import pytest
from decimal import Decimal
from snowflake.snowpark import Row
from snowflake.snowpark._internal.data_source.datasource_partitioner import (
DataSourcePartitioner,
)
from snowflake.snowpark._internal.data_source.datasource_reader import DataSourceReader
from snowflake.snowpark._internal.data_source.drivers import (
PyodbcDriver,
SqliteDriver,
BaseDriver,
)
from snowflake.snowpark._internal.data_source.utils import (
_task_fetch_data_from_source,
_upload_and_copy_into_table_with_retry,
_task_fetch_data_from_source_with_retry,
STATEMENT_PARAMS_DATA_SOURCE,
DATA_SOURCE_SQL_COMMENT,
DATA_SOURCE_DBAPI_SIGNATURE,
detect_dbms,
DBMS_TYPE,
DRIVER_TYPE,
worker_process,
PARTITION_TASK_COMPLETE_SIGNAL_PREFIX,
PARTITION_TASK_ERROR_SIGNAL,
process_completed_futures,
)
from snowflake.snowpark._internal.utils import (
TempObjectType,
random_name_for_temp_object,
)
from snowflake.snowpark.dataframe_reader import _MAX_RETRY_TIME
from snowflake.snowpark.exceptions import SnowparkDataframeReaderException
from snowflake.snowpark.types import (
StructType,
StructField,
IntegerType,
DateType,
MapType,
StringType,
BooleanType,
)
from tests.resources.test_data_source_dir.test_data_source_data import (
sql_server_all_type_data,
sql_server_all_type_small_data,
sql_server_create_connection,
sql_server_create_connection_small_data,
sql_server_create_connection_with_exception,
sqlite3_db,
create_connection_to_sqlite3_db,
OracleDBType,
sql_server_create_connection_empty_data,
unknown_dbms_create_connection,
sql_server_all_type_schema,
SQLITE3_DB_CUSTOM_SCHEMA_STRING,
SQLITE3_DB_CUSTOM_SCHEMA_STRUCT_TYPE,
sql_server_udtf_ingestion_data,
sql_server_create_connection_unicode_data,
sql_server_create_connection_double_quoted_data,
)
from tests.utils import Utils, IS_WINDOWS
try:
import pandas # noqa: F401
is_pandas_available = True
except ImportError:
is_pandas_available = False
pytestmark = [
pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="feature not available in local testing",
),
pytest.mark.skipif(
not is_pandas_available,
reason="pandas is not available",
),
]
SQL_SERVER_TABLE_NAME = "AllDataTypesTable"
ORACLEDB_TABLE_NAME = "ALL_TYPE_TABLE"
ORACLEDB_TABLE_NAME_SMALL = "ALL_TYPE_TABLE_SMALL"
ORACLEDB_TEST_EXTERNAL_ACCESS_INTEGRATION = "snowpark_dbapi_oracledb_test_integration"
@pytest.mark.parametrize(
"input_type, input_value",
[
("table", SQL_SERVER_TABLE_NAME),
("query", f"SELECT * FROM {SQL_SERVER_TABLE_NAME}"),
("query", f"(SELECT * FROM {SQL_SERVER_TABLE_NAME})"),
],
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_basic_sql_server(session, caplog, fetch_with_process, input_type, input_value):
input_dict = {
input_type: input_value,
"fetch_with_process": fetch_with_process,
}
with caplog.at_level(logging.DEBUG):
df = session.read.dbapi(sql_server_create_connection, **input_dict)
# default fetch size is 1k, so we should only see 1 parquet file generated as the data is less than 1k
assert caplog.text.count("Retrieved BytesIO parquet from queue") == 1
assert df.collect() == sql_server_all_type_data
@pytest.mark.parametrize(
"create_connection, table_name, expected_result",
[
(sql_server_create_connection, SQL_SERVER_TABLE_NAME, sql_server_all_type_data),
(
sql_server_create_connection_small_data,
SQL_SERVER_TABLE_NAME,
sql_server_all_type_small_data,
),
],
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
@pytest.mark.parametrize("fetch_size", [1, 3])
def test_dbapi_batch_fetch(
session,
create_connection,
table_name,
expected_result,
fetch_size,
caplog,
fetch_with_process,
):
with caplog.at_level(logging.DEBUG):
df = session.read.dbapi(
create_connection,
table=table_name,
max_workers=4,
fetch_size=fetch_size,
fetch_with_process=fetch_with_process,
)
# we only expect math.ceil(len(expected_result) / fetch_size) parquet files to be generated
# for example, 5 rows, fetch size 2, we expect 3 parquet files
assert caplog.text.count("Retrieved BytesIO parquet from queue") == math.ceil(
len(expected_result) / fetch_size
)
assert df.order_by("ID").collect() == expected_result
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_dbapi_retry(session, fetch_with_process):
with mock.patch(
"snowflake.snowpark._internal.data_source.utils._task_fetch_data_from_source",
side_effect=RuntimeError("Test error"),
) as mock_task:
mock_task.__name__ = "_task_fetch_from_data_source"
parquet_queue = multiprocessing.Queue() if fetch_with_process else queue.Queue()
with pytest.raises(
SnowparkDataframeReaderException, match="\\[RuntimeError\\] Test error"
):
_task_fetch_data_from_source_with_retry(
worker=DataSourceReader(
PyodbcDriver,
sql_server_create_connection,
StructType([StructField("col1", IntegerType(), False)]),
DBMS_TYPE.SQL_SERVER_DB,
),
partition="SELECT * FROM test_table",
partition_idx=0,
parquet_queue=parquet_queue,
)
assert mock_task.call_count == _MAX_RETRY_TIME
with mock.patch(
"snowflake.snowpark._internal.data_source.utils._upload_and_copy_into_table",
side_effect=RuntimeError("Test error"),
) as mock_task:
mock_task.__name__ = "_upload_and_copy_into_table"
with pytest.raises(
SnowparkDataframeReaderException, match="\\[RuntimeError\\] Test error"
):
back_pressure = threading.BoundedSemaphore()
back_pressure.acquire()
_upload_and_copy_into_table_with_retry(
session=session,
parquet_id="test.parquet",
parquet_buffer=BytesIO(b"test data"),
snowflake_stage_name="fake_stage",
backpressure_semaphore=back_pressure,
snowflake_table_name="fake_table",
)
assert mock_task.call_count == _MAX_RETRY_TIME
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_dbapi_non_retryable_error(session, fetch_with_process):
with mock.patch(
"snowflake.snowpark._internal.data_source.utils._task_fetch_data_from_source",
side_effect=SnowparkDataframeReaderException("mock error"),
) as mock_task:
mock_task.__name__ = "_task_fetch_from_data_source"
parquet_queue = multiprocessing.Queue() if fetch_with_process else queue.Queue()
with pytest.raises(SnowparkDataframeReaderException, match="mock error"):
_task_fetch_data_from_source_with_retry(
worker=DataSourceReader(
PyodbcDriver,
sql_server_create_connection,
StructType([StructField("col1", IntegerType(), False)]),
DBMS_TYPE.SQL_SERVER_DB,
),
partition="SELECT * FROM test_table",
partition_idx=0,
parquet_queue=parquet_queue,
)
assert mock_task.call_count == 1
@pytest.mark.skipif(
IS_WINDOWS,
reason="sqlite3 file can not be shared across processes on windows",
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
@pytest.mark.parametrize("upper_bound, expected_upload_cnt", [(5, 3), (100, 1)])
def test_parallel(session, upper_bound, expected_upload_cnt, fetch_with_process):
num_partitions = 3
with tempfile.TemporaryDirectory() as temp_dir:
dbpath = os.path.join(temp_dir, "testsqlite3.db")
table_name, _, _, assert_data = sqlite3_db(dbpath)
with mock.patch(
"snowflake.snowpark._internal.data_source.utils._upload_and_copy_into_table_with_retry",
wraps=_upload_and_copy_into_table_with_retry,
) as mock_upload_and_copy:
df = session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
table=table_name,
column="id",
upper_bound=upper_bound,
lower_bound=0,
num_partitions=num_partitions,
max_workers=4,
custom_schema=SQLITE3_DB_CUSTOM_SCHEMA_STRING,
fetch_with_process=fetch_with_process,
)
assert mock_upload_and_copy.call_count == expected_upload_cnt
assert df.order_by("ID").collect() == assert_data
@pytest.mark.parametrize(
"schema, raw_schema, column, lower_bound, upper_bound, num_partitions, expected_queries",
[
(
StructType([StructField("ID", IntegerType())]),
[("ID", int)],
"ID",
5,
15,
4,
[
"SELECT \"ID\" FROM fake_table WHERE ID < '8' OR ID is null",
"SELECT \"ID\" FROM fake_table WHERE ID >= '8' AND ID < '10'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '10' AND ID < '12'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '12'",
],
),
(
StructType([StructField("ID", IntegerType())]),
[("ID", int)],
"ID",
-5,
5,
4,
[
"SELECT \"ID\" FROM fake_table WHERE ID < '-2' OR ID is null",
"SELECT \"ID\" FROM fake_table WHERE ID >= '-2' AND ID < '0'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '0' AND ID < '2'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '2'",
],
),
(
StructType([StructField("ID", IntegerType())]),
[("ID", int)],
"ID",
5,
15,
10,
[
"SELECT \"ID\" FROM fake_table WHERE ID < '6' OR ID is null",
"SELECT \"ID\" FROM fake_table WHERE ID >= '6' AND ID < '7'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '7' AND ID < '8'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '8' AND ID < '9'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '9' AND ID < '10'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '10' AND ID < '11'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '11' AND ID < '12'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '12' AND ID < '13'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '13' AND ID < '14'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '14'",
],
),
(
StructType([StructField("ID", IntegerType())]),
[("ID", int)],
"ID",
5,
15,
3,
[
"SELECT \"ID\" FROM fake_table WHERE ID < '8' OR ID is null",
"SELECT \"ID\" FROM fake_table WHERE ID >= '8' AND ID < '11'",
"SELECT \"ID\" FROM fake_table WHERE ID >= '11'",
],
),
(
StructType([StructField("DATE", DateType())]),
[("DATE", datetime.datetime)],
"DATE",
str(datetime.date(2020, 6, 15)),
str(datetime.date(2020, 12, 15)),
4,
[
"SELECT \"DATE\" FROM fake_table WHERE DATE < '2020-07-30 18:00:00+00:00' OR DATE is null",
"SELECT \"DATE\" FROM fake_table WHERE DATE >= '2020-07-30 18:00:00+00:00' AND DATE < '2020-09-14 12:00:00+00:00'",
"SELECT \"DATE\" FROM fake_table WHERE DATE >= '2020-09-14 12:00:00+00:00' AND DATE < '2020-10-30 06:00:00+00:00'",
"SELECT \"DATE\" FROM fake_table WHERE DATE >= '2020-10-30 06:00:00+00:00'",
],
),
(
StructType([StructField("DATE", DateType())]),
[("DATE", datetime.datetime)],
"DATE",
str(datetime.datetime(2020, 6, 15, 12, 25, 30)),
str(datetime.datetime(2020, 12, 15, 7, 8, 20)),
4,
[
"SELECT \"DATE\" FROM fake_table WHERE DATE < '2020-07-31 05:06:13+00:00' OR DATE is null",
"SELECT \"DATE\" FROM fake_table WHERE DATE >= '2020-07-31 05:06:13+00:00' AND DATE < '2020-09-14 21:46:55+00:00'",
"SELECT \"DATE\" FROM fake_table WHERE DATE >= '2020-09-14 21:46:55+00:00' AND DATE < '2020-10-30 14:27:37+00:00'",
"SELECT \"DATE\" FROM fake_table WHERE DATE >= '2020-10-30 14:27:37+00:00'",
],
),
],
)
def test_partition_logic(
session,
schema,
raw_schema,
column,
lower_bound,
upper_bound,
num_partitions,
expected_queries,
):
with patch.object(
DataSourcePartitioner, "schema", new_callable=PropertyMock
) as mock_schema:
partitioner = DataSourcePartitioner(
sql_server_create_connection,
table_or_query="fake_table",
is_query=False,
column=column,
lower_bound=lower_bound,
upper_bound=upper_bound,
num_partitions=num_partitions,
)
mock_schema.return_value = schema
partitioner.driver.raw_schema = raw_schema
queries = partitioner.partitions
for r, expected_r in zip(queries, expected_queries):
assert r == expected_r
def test_partition_unsupported_type(session):
with pytest.raises(ValueError, match="unsupported type"):
with patch.object(
DataSourcePartitioner, "schema", new_callable=PropertyMock
) as mock_schema:
partitioner = DataSourcePartitioner(
sql_server_create_connection,
table_or_query="fake_table",
is_query=False,
column="DATE",
lower_bound=0,
upper_bound=1,
num_partitions=4,
)
mock_schema.return_value = StructType(
[StructField("DATE", MapType(), False)]
)
partitioner.driver.raw_schema = [("DATE", dict)]
partitioner.partitions
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_telemetry(session, fetch_with_process, caplog):
with patch(
"snowflake.snowpark._internal.telemetry.TelemetryClient.send_data_source_perf_telemetry"
) as mock_telemetry:
df = session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
fetch_with_process=fetch_with_process,
)
telemetry_json = mock_telemetry.call_args[0][0]
assert telemetry_json["function_name"] == "DataFrameReader.dbapi"
assert telemetry_json["ingestion_mode"] == "local_ingestion"
assert telemetry_json["dbms_type"] == DBMS_TYPE.SQL_SERVER_DB.value
assert telemetry_json["driver_type"] == DRIVER_TYPE.PYODBC.value
assert telemetry_json["schema"] == df.schema.simple_string()
assert "fetch_to_local_duration" in telemetry_json
assert "upload_and_copy_into_sf_table_duration" in telemetry_json
assert "end_to_end_duration" in telemetry_json
assert "upload and copy into table start" in caplog.text
if not fetch_with_process:
assert "fetch start" in caplog.text
assert "upload and copy into table finished, used" in caplog.text
if not fetch_with_process:
assert "fetch finished, used" in caplog.text
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_telemetry_tracking(caplog, session, fetch_with_process):
original_func = session._conn.run_query
called, comment_showed = 0, 0
def assert_datasource_statement_params_run_query(*args, **kwargs):
# assert we set statement_parameters to track datasource api usage
nonlocal comment_showed
statement_parameters = kwargs.get("_statement_params")
query = args[0]
if not query.lower().startswith("put"):
# put_stream does not accept statement_params
assert statement_parameters[STATEMENT_PARAMS_DATA_SOURCE] == "1"
if "select" not in query.lower() and "put" not in query.lower():
assert DATA_SOURCE_SQL_COMMENT in query
comment_showed += 1
nonlocal called
called += 1
return original_func(*args, **kwargs)
with mock.patch(
"snowflake.snowpark._internal.server_connection.ServerConnection.run_query",
side_effect=assert_datasource_statement_params_run_query,
), mock.patch(
"snowflake.snowpark._internal.telemetry.TelemetryClient.send_performance_telemetry"
) as mock_telemetry:
df = session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
fetch_with_process=fetch_with_process,
)
assert df._plan.api_calls == [{"name": DATA_SOURCE_DBAPI_SIGNATURE}]
assert (
called == 4 and comment_showed == 3
) # 4 queries: create table, create stage, put file, copy into
assert mock_telemetry.called
assert df.collect() == sql_server_all_type_data
# assert when we save/copy, the statement_params is added
temp_table = Utils.random_name_for_temp_object(TempObjectType.TABLE)
temp_stage = Utils.random_name_for_temp_object(TempObjectType.STAGE)
Utils.create_stage(session, temp_stage, is_temporary=True)
called = 0
with mock.patch(
"snowflake.snowpark._internal.server_connection.ServerConnection.run_query",
side_effect=assert_datasource_statement_params_run_query,
):
df.write.save_as_table(temp_table)
df.write.copy_into_location(
f"{temp_stage}/test.parquet",
file_format_type="parquet",
header=True,
overwrite=True,
single=True,
)
assert called == 2
def test_telemetry_tracking_for_udtf(caplog, session):
original_func = session._conn.run_query
called = 0
def assert_datasource_statement_params_run_query(*args, **kwargs):
# assert we set statement_parameters to track datasource udtf api usage
assert kwargs.get("_statement_params")[STATEMENT_PARAMS_DATA_SOURCE] == "1"
nonlocal called
called += 1
return original_func(*args, **kwargs)
def create_connection():
class FakeConnection:
def cursor(self):
class FakeCursor:
def execute(self, query):
pass
@property
def description(self):
return [("c1", int, None, None, None, None, None)]
def fetchmany(self, *args, **kwargs):
return None
return FakeCursor()
return FakeConnection()
df = session.read.dbapi(
create_connection,
table="Fake",
custom_schema="c1 INT",
udtf_configs={
"external_access_integration": ORACLEDB_TEST_EXTERNAL_ACCESS_INTEGRATION,
"packages": ["snowflake-snowpark-python"],
},
)
with mock.patch(
"snowflake.snowpark._internal.server_connection.ServerConnection.run_query",
side_effect=assert_datasource_statement_params_run_query,
):
df.select("*").collect()
assert (
"'name': 'DataFrameReader.dbapi'" in str(df._plan.api_calls[0]) and called == 1
)
@pytest.mark.skipif(
IS_WINDOWS,
reason="sqlite3 file can not be shared accorss processes on windows",
)
@pytest.mark.parametrize(
"custom_schema",
[SQLITE3_DB_CUSTOM_SCHEMA_STRING, SQLITE3_DB_CUSTOM_SCHEMA_STRUCT_TYPE],
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_custom_schema(session, custom_schema, fetch_with_process):
with tempfile.TemporaryDirectory() as temp_dir:
dbpath = os.path.join(temp_dir, "testsqlite3.db")
table_name, columns, example_data, assert_data = sqlite3_db(dbpath)
df = session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
table=table_name,
custom_schema=custom_schema,
fetch_with_process=fetch_with_process,
)
assert df.columns == [col.upper() for col in columns]
assert df.collect() == assert_data
with pytest.raises(
SnowparkDataframeReaderException,
match="Auto infer schema failure:",
):
session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
table=table_name,
)
def test_predicates():
with patch.object(
DataSourcePartitioner, "schema", new_callable=PropertyMock
) as mock_schema:
partitioner = DataSourcePartitioner(
sql_server_create_connection,
table_or_query="fake_table",
is_query=False,
predicates=[
"id > 1 AND id <= 1000",
"id > 1001 AND id <= 2000",
"id > 2001",
],
)
partitioner.driver.raw_schema = [("ID", int)]
mock_schema.return_value = StructType([StructField("ID", IntegerType(), False)])
queries = partitioner.partitions
expected_result = [
'SELECT "ID" FROM fake_table WHERE id > 1 AND id <= 1000',
'SELECT "ID" FROM fake_table WHERE id > 1001 AND id <= 2000',
'SELECT "ID" FROM fake_table WHERE id > 2001',
]
assert queries == expected_result
@pytest.mark.skipif(
IS_WINDOWS,
reason="sqlite3 file can not be shared across processes on windows",
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_session_init_statement(session, fetch_with_process):
with tempfile.TemporaryDirectory() as temp_dir:
dbpath = os.path.join(temp_dir, "testsqlite3.db")
table_name, columns, example_data, assert_data = sqlite3_db(dbpath)
new_data1 = (8, 100) + (None,) * (len(columns) - 3) + ('"123"',)
new_data2 = (9, 101) + (None,) * (len(columns) - 3) + ('"456"',)
df = session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
table=table_name,
custom_schema=SQLITE3_DB_CUSTOM_SCHEMA_STRING,
session_init_statement=f"insert into {table_name} (int_col, var_col) values (100, '123');",
fetch_with_process=fetch_with_process,
)
assert df.collect() == assert_data + [new_data1]
df = session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
table=table_name,
custom_schema=SQLITE3_DB_CUSTOM_SCHEMA_STRING,
session_init_statement=[
f"insert into {table_name} (int_col, var_col) values (100, '123');",
f"insert into {table_name} (int_col, var_col) values (101, '456');",
],
)
assert df.collect() == assert_data + [new_data1, new_data2]
with pytest.raises(
SnowparkDataframeReaderException,
match="Failed to execute session init statement:",
):
session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
table=table_name,
custom_schema="id INTEGER",
session_init_statement="SELECT FROM NOTHING;",
fetch_with_process=fetch_with_process,
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_negative_case(session, fetch_with_process):
# error happening in fetching
with pytest.raises(
SnowparkDataframeReaderException, match="RuntimeError: Fake exception"
):
session.read.dbapi(
sql_server_create_connection_with_exception, table=SQL_SERVER_TABLE_NAME
)
# error happening during ingestion
with mock.patch(
"snowflake.snowpark._internal.data_source.utils._upload_and_copy_into_table",
side_effect=ValueError("Ingestion exception"),
) as mock_task:
mock_task.__name__ = "_upload_and_copy_into_table"
with pytest.raises(
SnowparkDataframeReaderException, match="ValueError: Ingestion exception"
):
session.read.dbapi(
sql_server_create_connection_small_data,
table=SQL_SERVER_TABLE_NAME,
fetch_with_process=fetch_with_process,
)
@pytest.mark.parametrize(
"fetch_size, partition_idx, expected_error",
[(0, 1, False), (2, 100, False), (10, 2, False), (-1, 1001, True)],
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_task_fetch_from_data_source_with_fetch_size(
fetch_size, partition_idx, expected_error, fetch_with_process
):
partitioner = DataSourcePartitioner(
sql_server_create_connection_small_data,
table_or_query="fake",
is_query=False,
fetch_size=fetch_size,
)
schema = partitioner.schema
file_count = (
math.ceil(len(sql_server_all_type_small_data) / fetch_size)
if fetch_size != 0
else 1
)
parquet_queue = multiprocessing.Queue() if fetch_with_process else queue.Queue()
params = {
"worker": DataSourceReader(
PyodbcDriver,
sql_server_create_connection_small_data,
schema=schema,
dbms_type=DBMS_TYPE.SQL_SERVER_DB,
fetch_size=fetch_size,
),
"partition": "SELECT * FROM test_table",
"partition_idx": partition_idx,
"parquet_queue": parquet_queue,
}
if expected_error:
with pytest.raises(
ValueError,
match="fetch size cannot be smaller than 0",
):
_task_fetch_data_from_source(**params)
else:
_task_fetch_data_from_source(**params)
# Collect all parquet data from the queue
parquet_files = []
completion_signal_received = False
timeout = 5.0 # 5 second timeout
# Keep draining the queue until we get the completion signal or timeout
while not completion_signal_received:
try:
parquet_id, parquet_buffer = parquet_queue.get(timeout=timeout)
# Check for completion signal
if parquet_id.startswith(PARTITION_TASK_COMPLETE_SIGNAL_PREFIX):
completion_signal_received = True
continue
# Verify parquet file naming pattern
assert parquet_id.startswith(
f"data_partition{partition_idx}_fetch"
), f"Unexpected parquet ID: {parquet_id}"
assert parquet_id.endswith(
".parquet"
), f"Parquet ID should end with .parquet: {parquet_id}"
# Verify parquet_buffer is a BytesIO object
assert isinstance(
parquet_buffer, BytesIO
), f"Expected BytesIO, got {type(parquet_buffer)}"
parquet_files.append((parquet_id, parquet_buffer))
except queue.Empty:
pytest.fail(
f"Timeout waiting for completion signal after {timeout} seconds"
)
# Verify we received the completion signal
assert (
completion_signal_received
), "Should have received partition completion signal"
# Verify the number of parquet files matches expected count
assert (
len(parquet_files) == file_count
), f"Expected {file_count} parquet files, got {len(parquet_files)}"
# Verify the parquet files are named correctly in sequence
for idx, (parquet_id, _) in enumerate(parquet_files):
expected_name = f"data_partition{partition_idx}_fetch{idx}.parquet"
assert (
expected_name in parquet_id
), f"Expected {expected_name} in {parquet_id}"
def test_database_detector():
mock_conn = MagicMock()
with patch.object(type(mock_conn), "__module__", "UNKNOWN_DRIVER"):
result = detect_dbms(mock_conn)
assert result == (DBMS_TYPE.UNKNOWN, DRIVER_TYPE.UNKNOWN)
mock_conn = MagicMock()
mock_conn.getinfo.return_value = "UNKNOWN"
with patch.object(type(mock_conn), "__module__", "pyodbc"):
result = detect_dbms(mock_conn)
assert result == (DBMS_TYPE.UNKNOWN, DRIVER_TYPE.PYODBC)
def test_unsupported_type():
invalid_type = OracleDBType("ID", "UNKNOWN", None, None, False)
schema = PyodbcDriver(
sql_server_create_connection, DBMS_TYPE.SQL_SERVER_DB
).to_snow_type([("test_col", invalid_type, None, None, 0, 0, True)])
assert schema == StructType([StructField("TEST_COL", StringType(), nullable=True)])
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_custom_schema_false(session, fetch_with_process):
with pytest.raises(ValueError, match="Invalid schema string: timestamp_tz."):
session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
max_workers=4,
custom_schema="timestamp_tz",
fetch_with_process=fetch_with_process,
)
with pytest.raises(ValueError, match="Invalid schema type: <class 'int'>."):
session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
max_workers=4,
custom_schema=1,
fetch_with_process=fetch_with_process,
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_partition_wrong_input(session, caplog, fetch_with_process):
with pytest.raises(
ValueError,
match="when column is not specified, lower_bound, upper_bound, num_partitions are expected to be None",
):
session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
lower_bound=0,
fetch_with_process=fetch_with_process,
)
with pytest.raises(
ValueError,
match="when column is specified, lower_bound, upper_bound, num_partitions must be specified",
):
session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
column="id",
fetch_with_process=fetch_with_process,
)
with pytest.raises(
ValueError, match="Specified column non_exist_column does not exist"
):
session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
column="non_exist_column",
lower_bound=0,
upper_bound=10,
num_partitions=2,
custom_schema=StructType([StructField("ID", IntegerType(), False)]),
fetch_with_process=fetch_with_process,
)
with pytest.raises(ValueError, match="unsupported type BooleanType()"):
session.read.dbapi(
sql_server_create_connection,
table=SQL_SERVER_TABLE_NAME,
column="ID",
lower_bound=0,
upper_bound=10,
num_partitions=2,
custom_schema=StructType([StructField("ID", BooleanType(), False)]),
fetch_with_process=fetch_with_process,
)
with patch.object(
DataSourcePartitioner, "schema", new_callable=PropertyMock
) as mock_schema:
with pytest.raises(
ValueError, match="lower_bound cannot be greater than upper_bound"
):
partitioner = DataSourcePartitioner(
sql_server_create_connection,
table_or_query="fake_table",
is_query=False,
column="DATE",
lower_bound=10,
upper_bound=1,
num_partitions=4,
)
mock_schema.return_value = StructType(
[StructField("DATE", IntegerType(), False)]
)
partitioner.driver.raw_schema = [("DATE", int)]
partitioner.partitions
partitioner = DataSourcePartitioner(
sql_server_create_connection,
table_or_query="fake_table",
is_query=False,
column="DATE",
lower_bound=0,
upper_bound=10,
num_partitions=20,
)
mock_schema.return_value = StructType(
[StructField("DATE", IntegerType(), False)]
)
partitioner.driver.raw_schema = [("DATE", int)]
partitioner.partitions
assert "The number of partitions is reduced" in caplog.text
@pytest.mark.skipif(
IS_WINDOWS,
reason="sqlite3 file can not be shared across processes on windows",
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_query_parameter(session, fetch_with_process):
with tempfile.TemporaryDirectory() as temp_dir:
dbpath = os.path.join(temp_dir, "testsqlite3.db")
table_name, columns, example_data, assert_data = sqlite3_db(dbpath)
filter_idx = 2
with pytest.raises(SnowparkDataframeReaderException, match="but not both"):
session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
table=table_name,
query=f"(SELECT * FROM PrimitiveTypes WHERE id > {filter_idx}) as t",
fetch_with_process=fetch_with_process,
)
df = session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
query=f"(SELECT * FROM PrimitiveTypes WHERE id > {filter_idx}) as t",
custom_schema=SQLITE3_DB_CUSTOM_SCHEMA_STRING,
fetch_with_process=fetch_with_process,
)
assert df.columns == [col.upper() for col in columns]
assert df.collect() == assert_data[filter_idx:]
def sqlite_to_snowpark_type(schema):
assert (
len(schema) == 2
and schema[0][0] == "int_col"
and schema[1][0] == "text_col"
)
return StructType(
[
StructField("int_col", IntegerType()),
StructField("text_col", StringType()),
]
)
with mock.patch(
"snowflake.snowpark._internal.data_source.drivers.sqlite_driver.SqliteDriver.to_snow_type",
side_effect=sqlite_to_snowpark_type,
):
query = (
f"SELECT int_col, text_col FROM PrimitiveTypes WHERE id > {filter_idx}"
)
df = session.read.dbapi(
functools.partial(create_connection_to_sqlite3_db, dbpath),
query=f"({query}) as t",
fetch_with_process=fetch_with_process,
)
assert df.columns == ["INT_COL", "TEXT_COL"]
assert (
df.collect()
== create_connection_to_sqlite3_db(dbpath).execute(query).fetchall()
)
@pytest.mark.skipif(
"config.getoption('enable_ast', default=False)",
reason="SNOW-1961756: Data source APIs not supported by AST",
)
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_option_load(session, fetch_with_process):
df = (
session.read.format("dbapi")
.option("create_connection", sql_server_create_connection)
.option("table", SQL_SERVER_TABLE_NAME)
.option("max_workers", 4)
.option("fetch_size", 2)
.option("fetch_with_process", fetch_with_process)
.load()
)
assert df.order_by("ID").collect() == sql_server_all_type_data
with pytest.raises(TypeError):
session.read.format("json").load()
with pytest.raises(ValueError):
session.read.format("dbapi").load("path")
with pytest.raises(
TypeError, match="missing 1 required positional argument: 'create_connection'"
):
session.read.format("dbapi").load()
@pytest.mark.parametrize("fetch_with_process", [True, False])
def test_empty_table(session, fetch_with_process):
df = session.read.dbapi(
sql_server_create_connection_empty_data,
table=SQL_SERVER_TABLE_NAME,
fetch_with_process=fetch_with_process,
)
assert df.collect() == []