-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathdataframe_reader.py
More file actions
1322 lines (1169 loc) · 54.3 KB
/
dataframe_reader.py
File metadata and controls
1322 lines (1169 loc) · 54.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
#
# Copyright (c) 2012-2024 Snowflake Computing Inc. All rights reserved.
#
import datetime
import decimal
import os
import tempfile
from concurrent.futures import (
ProcessPoolExecutor,
wait,
ALL_COMPLETED,
ThreadPoolExecutor,
as_completed,
)
from dateutil import parser
import sys
from logging import getLogger
from typing import Any, Dict, List, Literal, Optional, Tuple, Union, Callable
import snowflake.snowpark
import snowflake.snowpark._internal.proto.generated.ast_pb2 as proto
from snowflake.snowpark._internal.analyzer.analyzer_utils import (
create_file_format_statement,
drop_file_format_if_exists_statement,
infer_schema_statement,
quote_name_without_upper_casing,
)
from snowflake.snowpark._internal.analyzer.expression import Attribute
from snowflake.snowpark._internal.analyzer.unary_expression import Alias
from snowflake.snowpark._internal.ast.utils import (
build_expr_from_python_val,
build_proto_from_struct_type,
build_sp_table_name,
with_src_position,
)
from snowflake.snowpark._internal.error_message import SnowparkClientExceptionMessages
from snowflake.snowpark._internal.telemetry import set_api_call_source
from snowflake.snowpark._internal.type_utils import (
ColumnOrName,
convert_sf_to_sp_type,
Connection,
)
from snowflake.snowpark._internal.utils import (
INFER_SCHEMA_FORMAT_TYPES,
SNOWFLAKE_PATH_PREFIXES,
TempObjectType,
get_aliased_option_name,
get_copy_into_table_options,
parse_positional_args_to_list_variadic,
publicapi,
get_temp_type_for_object,
)
from snowflake.snowpark.column import METADATA_COLUMN_TYPES, Column, _to_col_if_str
from snowflake.snowpark.dataframe import DataFrame
from snowflake.snowpark.exceptions import (
SnowparkSessionException,
SnowparkClientException,
)
from snowflake.snowpark.functions import sql_expr
from snowflake.snowpark.mock._connection import MockServerConnection
from snowflake.snowpark.table import Table
from snowflake.snowpark.types import (
StructType,
VariantType,
StructField,
IntegerType,
FloatType,
DecimalType,
StringType,
DateType,
BooleanType,
DataType,
_NumericType,
TimestampType,
)
from snowflake.connector.options import pandas as pd
from snowflake.snowpark._internal.utils import random_name_for_temp_object
# Python 3.8 needs to use typing.Iterable because collections.abc.Iterable is not subscriptable
# Python 3.9 can use both
# Python 3.10 needs to use collections.abc.Iterable because typing.Iterable is removed
if sys.version_info <= (3, 9):
from typing import Iterable
else:
from collections.abc import Iterable
logger = getLogger(__name__)
LOCAL_TESTING_SUPPORTED_FILE_FORMAT = ("JSON",)
READER_OPTIONS_ALIAS_MAP = {
"DELIMITER": "FIELD_DELIMITER",
"HEADER": "PARSE_HEADER",
"PATHGLOBFILTER": "PATTERN",
"FILENAMEPATTERN": "PATTERN",
"INFERSCHEMA": "INFER_SCHEMA",
"SEP": "FIELD_DELIMITER",
"LINESEP": "RECORD_DELIMITER",
"QUOTE": "FIELD_OPTIONALLY_ENCLOSED_BY",
"NULLVALUE": "NULL_IF",
"DATEFORMAT": "DATE_FORMAT",
"TIMESTAMPFORMAT": "TIMESTAMP_FORMAT",
}
MAX_RETRY_TIME = 3
def _validate_stage_path(path: str) -> str:
stripped_path = path.strip("\"'")
if not any(stripped_path.startswith(prefix) for prefix in SNOWFLAKE_PATH_PREFIXES):
raise ValueError(
f"'{path}' is an invalid Snowflake stage location. DataFrameReader can only read files from stage locations."
)
return path
class DataFrameReader:
"""Provides methods to load data in various supported formats from a Snowflake
stage to a :class:`DataFrame`. The paths provided to the DataFrameReader must refer
to Snowflake stages.
To use this object:
1. Access an instance of a :class:`DataFrameReader` by using the
:attr:`Session.read` property.
2. Specify any `format-specific options <https://docs.snowflake.com/en/sql-reference/sql/create-file-format.html#format-type-options-formattypeoptions>`_ and `copy options <https://docs.snowflake.com/en/sql-reference/sql/copy-into-table.html#copy-options-copyoptions>`_
by calling the :func:`option` or :func:`options` method. These methods return a
DataFrameReader that is configured with these options. (Note that although
specifying copy options can make error handling more robust during the reading
process, it may have an effect on performance.)
3. Specify the schema of the data that you plan to load by constructing a
:class:`types.StructType` object and passing it to the :func:`schema` method if the file format is CSV. Other file
formats such as JSON, XML, Parquet, ORC, and AVRO don't accept a schema.
This method returns a :class:`DataFrameReader` that is configured to read data that uses the specified schema.
Currently, inferring schema is also supported for CSV and JSON formats as a preview feature open to all accounts.
4. Specify the format of the data by calling the method named after the format
(e.g. :func:`csv`, :func:`json`, etc.). These methods return a :class:`DataFrame`
that is configured to load data in the specified format.
5. Call a :class:`DataFrame` method that performs an action (e.g.
:func:`DataFrame.collect`) to load the data from the file.
The following examples demonstrate how to use a DataFrameReader.
>>> # Create a temp stage to run the example code.
>>> _ = session.sql("CREATE or REPLACE temp STAGE mystage").collect()
Example 1:
Loading the first two columns of a CSV file and skipping the first header line:
>>> from snowflake.snowpark.types import StructType, StructField, IntegerType, StringType, FloatType
>>> _ = session.file.put("tests/resources/testCSV.csv", "@mystage", auto_compress=False)
>>> # Define the schema for the data in the CSV file.
>>> user_schema = StructType([StructField("a", IntegerType()), StructField("b", StringType()), StructField("c", FloatType())])
>>> # Create a DataFrame that is configured to load data from the CSV file.
>>> df = session.read.options({"field_delimiter": ",", "skip_header": 1}).schema(user_schema).csv("@mystage/testCSV.csv")
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.collect()
[Row(A=2, B='two', C=2.2)]
Example 2:
Loading a gzip compressed json file:
>>> _ = session.file.put("tests/resources/testJson.json", "@mystage", auto_compress=True)
>>> # Create a DataFrame that is configured to load data from the gzipped JSON file.
>>> json_df = session.read.option("compression", "gzip").json("@mystage/testJson.json.gz")
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> json_df.show()
-----------------------
|"$1" |
-----------------------
|{ |
| "color": "Red", |
| "fruit": "Apple", |
| "size": "Large" |
|} |
-----------------------
<BLANKLINE>
In addition, if you want to load only a subset of files from the stage, you can use the
`pattern <https://docs.snowflake.com/en/sql-reference/sql/copy-into-table.html#loading-using-pattern-matching>`_
option to specify a regular expression that matches the files that you want to load.
Example 3:
Loading only the CSV files from a stage location:
>>> from snowflake.snowpark.types import StructType, StructField, IntegerType, StringType
>>> from snowflake.snowpark.functions import col
>>> _ = session.file.put("tests/resources/*.csv", "@mystage", auto_compress=False)
>>> # Define the schema for the data in the CSV files.
>>> user_schema = StructType([StructField("a", IntegerType()), StructField("b", StringType()), StructField("c", FloatType())])
>>> # Create a DataFrame that is configured to load data from the CSV files in the stage.
>>> csv_df = session.read.option("pattern", ".*V[.]csv").schema(user_schema).csv("@mystage").sort(col("a"))
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> csv_df.collect()
[Row(A=1, B='one', C=1.2), Row(A=2, B='two', C=2.2), Row(A=3, B='three', C=3.3), Row(A=4, B='four', C=4.4)]
To load Parquet, ORC and AVRO files, no schema is accepted because the schema will be automatically inferred.
Inferring the schema can be disabled by setting option "infer_schema" to ``False``. Then you can use ``$1`` to access
the column data as an OBJECT.
Example 4:
Loading a Parquet file with inferring the schema.
>>> from snowflake.snowpark.functions import col
>>> _ = session.file.put("tests/resources/test.parquet", "@mystage", auto_compress=False)
>>> # Create a DataFrame that uses a DataFrameReader to load data from a file in a stage.
>>> df = session.read.parquet("@mystage/test.parquet").where(col('"num"') == 2)
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.collect()
[Row(str='str2', num=2)]
Example 5:
Loading an ORC file and infer the schema:
>>> from snowflake.snowpark.functions import col
>>> _ = session.file.put("tests/resources/test.orc", "@mystage", auto_compress=False)
>>> # Create a DataFrame that uses a DataFrameReader to load data from a file in a stage.
>>> df = session.read.orc("@mystage/test.orc").where(col('"num"') == 2)
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.collect()
[Row(str='str2', num=2)]
Example 6:
Loading an AVRO file and infer the schema:
>>> from snowflake.snowpark.functions import col
>>> _ = session.file.put("tests/resources/test.avro", "@mystage", auto_compress=False)
>>> # Create a DataFrame that uses a DataFrameReader to load data from a file in a stage.
>>> df = session.read.avro("@mystage/test.avro").where(col('"num"') == 2)
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.collect()
[Row(str='str2', num=2)]
Example 7:
Loading a Parquet file without inferring the schema:
>>> from snowflake.snowpark.functions import col
>>> _ = session.file.put("tests/resources/test.parquet", "@mystage", auto_compress=False)
>>> # Create a DataFrame that uses a DataFrameReader to load data from a file in a stage.
>>> df = session.read.option("infer_schema", False).parquet("@mystage/test.parquet").where(col('$1')["num"] == 2)
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.show()
-------------------
|"$1" |
-------------------
|{ |
| "num": 2, |
| "str": "str2" |
|} |
-------------------
<BLANKLINE>
Loading JSON and XML files doesn't support schema either. You also need to use ``$1`` to access the column data as an OBJECT.
Example 8:
Loading a JSON file:
>>> from snowflake.snowpark.functions import col, lit
>>> _ = session.file.put("tests/resources/testJson.json", "@mystage", auto_compress=False)
>>> # Create a DataFrame that uses a DataFrameReader to load data from a file in a stage.
>>> df = session.read.json("@mystage/testJson.json").where(col("$1")["fruit"] == lit("Apple"))
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.show()
-----------------------
|"$1" |
-----------------------
|{ |
| "color": "Red", |
| "fruit": "Apple", |
| "size": "Large" |
|} |
|{ |
| "color": "Red", |
| "fruit": "Apple", |
| "size": "Large" |
|} |
-----------------------
<BLANKLINE>
Example 9:
Loading an XML file:
>>> _ = session.file.put("tests/resources/test.xml", "@mystage", auto_compress=False)
>>> # Create a DataFrame that uses a DataFrameReader to load data from a file in a stage.
>>> df = session.read.xml("@mystage/test.xml")
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.show()
---------------------
|"$1" |
---------------------
|<test> |
| <num>1</num> |
| <str>str1</str> |
|</test> |
|<test> |
| <num>2</num> |
| <str>str2</str> |
|</test> |
---------------------
<BLANKLINE>
Example 10:
Loading a CSV file with an already existing FILE_FORMAT:
>>> from snowflake.snowpark.types import StructType, StructField, IntegerType, StringType
>>> _ = session.sql("create file format if not exists csv_format type=csv skip_header=1 null_if='none';").collect()
>>> _ = session.file.put("tests/resources/testCSVspecialFormat.csv", "@mystage", auto_compress=False)
>>> # Define the schema for the data in the CSV files.
>>> schema = StructType([StructField("ID", IntegerType()),StructField("USERNAME", StringType()),StructField("FIRSTNAME", StringType()),StructField("LASTNAME", StringType())])
>>> # Create a DataFrame that is configured to load data from the CSV files in the stage.
>>> df = session.read.schema(schema).option("format_name", "csv_format").csv("@mystage/testCSVspecialFormat.csv")
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.collect()
[Row(ID=0, USERNAME='admin', FIRSTNAME=None, LASTNAME=None), Row(ID=1, USERNAME='test_user', FIRSTNAME='test', LASTNAME='user')]
Example 11:
Querying metadata for staged files:
>>> from snowflake.snowpark.column import METADATA_FILENAME, METADATA_FILE_ROW_NUMBER
>>> df = session.read.with_metadata(METADATA_FILENAME, METADATA_FILE_ROW_NUMBER.as_("ROW NUMBER")).schema(user_schema).csv("@mystage/testCSV.csv")
>>> # Load the data into the DataFrame and return an array of rows containing the results.
>>> df.show()
--------------------------------------------------------
|"METADATA$FILENAME" |"ROW NUMBER" |"A" |"B" |"C" |
--------------------------------------------------------
|testCSV.csv |1 |1 |one |1.2 |
|testCSV.csv |2 |2 |two |2.2 |
--------------------------------------------------------
<BLANKLINE>
Example 12:
Inferring schema for csv and json files (Preview Feature - Open):
>>> # Read a csv file without a header
>>> df = session.read.option("INFER_SCHEMA", True).csv("@mystage/testCSV.csv")
>>> df.show()
----------------------
|"c1" |"c2" |"c3" |
----------------------
|1 |one |1.2 |
|2 |two |2.2 |
----------------------
<BLANKLINE>
>>> # Read a csv file with header and parse the header
>>> _ = session.file.put("tests/resources/testCSVheader.csv", "@mystage", auto_compress=False)
>>> df = session.read.option("INFER_SCHEMA", True).option("PARSE_HEADER", True).csv("@mystage/testCSVheader.csv")
>>> df.show()
----------------------------
|"id" |"name" |"rating" |
----------------------------
|1 |one |1.2 |
|2 |two |2.2 |
----------------------------
<BLANKLINE>
>>> df = session.read.option("INFER_SCHEMA", True).json("@mystage/testJson.json")
>>> df.show()
------------------------------
|"color" |"fruit" |"size" |
------------------------------
|Red |Apple |Large |
|Red |Apple |Large |
------------------------------
<BLANKLINE>
"""
@publicapi
def __init__(
self, session: "snowflake.snowpark.session.Session", _emit_ast: bool = True
) -> None:
self._session = session
self._user_schema: Optional[StructType] = None
self._cur_options: dict[str, Any] = {}
self._file_path: Optional[str] = None
self._file_type: Optional[str] = None
self._metadata_cols: Optional[Iterable[ColumnOrName]] = None
# Infer schema information
self._infer_schema_transformations: Optional[
List["snowflake.snowpark.column.Column"]
] = None
self._infer_schema_target_columns: Optional[List[str]] = None
self.__format: Optional[str] = None
self._ast = None
if _emit_ast:
reader = proto.SpDataframeReader()
with_src_position(reader.sp_dataframe_reader_init)
self._ast = reader
@property
def _infer_schema(self):
# let _cur_options to be the source of truth
if self._file_type in INFER_SCHEMA_FORMAT_TYPES:
return self._cur_options.get("INFER_SCHEMA", True)
return False
def _get_metadata_project_and_schema(self) -> Tuple[List[str], List[Attribute]]:
if self._metadata_cols:
metadata_project = [
self._session._analyzer.analyze(col._expression, {})
for col in self._metadata_cols
]
else:
metadata_project = []
metadata_schema = []
def _get_unaliased_name(unaliased: ColumnOrName) -> str:
if isinstance(unaliased, Column):
if isinstance(unaliased._expression, Alias):
return unaliased._expression.child.sql
return unaliased._named().name
return unaliased
try:
metadata_schema = [
Attribute(
metadata_col._named().name,
METADATA_COLUMN_TYPES[_get_unaliased_name(metadata_col).upper()],
)
for metadata_col in self._metadata_cols or []
]
except KeyError:
raise ValueError(
f"Metadata column name is not supported. Supported {METADATA_COLUMN_TYPES.keys()}, Got {metadata_project}"
)
return metadata_project, metadata_schema
@publicapi
def table(self, name: Union[str, Iterable[str]], _emit_ast: bool = True) -> Table:
"""Returns a Table that points to the specified table.
This method is an alias of :meth:`~snowflake.snowpark.session.Session.table`.
Args:
name: Name of the table to use.
"""
# AST.
stmt = None
if _emit_ast:
stmt = self._session._ast_batch.assign()
ast = with_src_position(stmt.expr.sp_read_table, stmt)
ast.reader.CopyFrom(self._ast)
build_sp_table_name(ast.name, name)
table = self._session.table(name)
if _emit_ast:
table._ast_id = stmt.var_id.bitfield1
return table
@publicapi
def schema(self, schema: StructType, _emit_ast: bool = True) -> "DataFrameReader":
"""Define the schema for CSV files that you want to read.
Args:
schema: Schema configuration for the CSV file to be read.
Returns:
a :class:`DataFrameReader` instance with the specified schema configuration for the data to be read.
"""
# AST.
if _emit_ast:
reader = proto.SpDataframeReader()
ast = with_src_position(reader.sp_dataframe_reader_schema)
ast.reader.CopyFrom(self._ast)
build_proto_from_struct_type(schema, ast.schema)
self._ast = reader
self._user_schema = schema
return self
@publicapi
def with_metadata(
self, *metadata_cols: Iterable[ColumnOrName], _emit_ast: bool = True
) -> "DataFrameReader":
"""Define the metadata columns that need to be selected from stage files.
Returns:
a :class:`DataFrameReader` instance with metadata columns to read.
See Also:
https://docs.snowflake.com/en/user-guide/querying-metadata
"""
if isinstance(self._session._conn, MockServerConnection):
self._session._conn.log_not_supported_error(
external_feature_name="DataFrameReader.with_metadata",
raise_error=NotImplementedError,
)
# AST.
if _emit_ast:
reader = proto.SpDataframeReader()
ast = with_src_position(reader.sp_dataframe_reader_with_metadata)
ast.reader.CopyFrom(self._ast)
col_names, is_variadic = parse_positional_args_to_list_variadic(
*metadata_cols
)
ast.metadata_columns.variadic = is_variadic
for e in col_names:
build_expr_from_python_val(ast.metadata_columns.args.add(), e)
self._ast = reader
self._metadata_cols = [
_to_col_if_str(col, "DataFrameReader.with_metadata")
for col in metadata_cols
]
return self
@property
def _format(self) -> Optional[str]:
return self.__format
@_format.setter
def _format(self, value: str) -> None:
canon_format = value.strip().lower()
allowed_formats = ["csv", "json", "avro", "parquet", "orc", "xml"]
if canon_format not in allowed_formats:
raise ValueError(
f"Invalid format '{value}'. Supported formats are {allowed_formats}."
)
self.__format = canon_format
def format(
self, format: Literal["csv", "json", "avro", "parquet", "orc", "xml"]
) -> "DataFrameReader":
"""Specify the format of the file(s) to load.
Args:
format: The format of the file(s) to load. Supported formats are csv, json, avro, parquet, orc, and xml.
Returns:
a :class:`DataFrameReader` instance that is set up to load data from the specified file format in a Snowflake stage.
"""
self._format = format
return self
def load(self, path: str) -> DataFrame:
"""Specify the path of the file(s) to load.
Args:
path: The stage location of a file, or a stage location that has files.
Returns:
a :class:`DataFrame` that is set up to load data from the specified file(s) in a Snowflake stage.
"""
if self._format is None:
raise ValueError(
"Please specify the format of the file(s) to load using the format() method."
)
loader = getattr(self, self._format, None)
if loader is not None:
return loader(path)
raise ValueError(f"Invalid format '{self._format}'.")
@publicapi
def csv(self, path: str, _emit_ast: bool = True) -> DataFrame:
"""Specify the path of the CSV file(s) to load.
Args:
path: The stage location of a CSV file, or a stage location that has CSV files.
Returns:
a :class:`DataFrame` that is set up to load data from the specified CSV file(s) in a Snowflake stage.
"""
path = _validate_stage_path(path)
self._file_path = path
self._file_type = "CSV"
schema_to_cast, transformations = None, None
if not self._user_schema:
if not self._infer_schema:
raise SnowparkClientExceptionMessages.DF_MUST_PROVIDE_SCHEMA_FOR_READING_FILE()
if isinstance(self._session._conn, MockServerConnection):
self._session._conn.log_not_supported_error(
external_feature_name="Read option 'INFER_SCHEMA of value 'TRUE' for file format 'csv'",
internal_feature_name="DataFrameReader.csv",
parameters_info={
"format": "csv",
"option": "INFER_SCHEMA",
"option_value": "TRUE",
},
raise_error=NotImplementedError,
)
(
schema,
schema_to_cast,
transformations,
exception,
) = self._infer_schema_for_file_format(path, "CSV")
if exception is not None:
if isinstance(exception, FileNotFoundError):
raise exception
# if infer schema query fails, use $1, VariantType as schema
logger.warn(
f"Could not infer csv schema due to exception: {exception}. "
"\nUsing schema (C1, VariantType()) instead. Please use DataFrameReader.schema() "
"to specify user schema for the file."
)
schema = [Attribute('"C1"', VariantType(), True)]
schema_to_cast = [("$1", "C1")]
transformations = []
else:
self._cur_options["INFER_SCHEMA"] = False
schema = self._user_schema._to_attributes()
metadata_project, metadata_schema = self._get_metadata_project_and_schema()
if self._session.sql_simplifier_enabled:
df = DataFrame(
self._session,
self._session._analyzer.create_select_statement(
from_=self._session._analyzer.create_select_snowflake_plan(
self._session._analyzer.plan_builder.read_file(
path,
self._file_type,
self._cur_options,
schema,
schema_to_cast=schema_to_cast,
transformations=transformations,
metadata_project=metadata_project,
metadata_schema=metadata_schema,
),
analyzer=self._session._analyzer,
),
analyzer=self._session._analyzer,
),
)
else:
df = DataFrame(
self._session,
self._session._plan_builder.read_file(
path,
self._file_type,
self._cur_options,
schema,
schema_to_cast=schema_to_cast,
transformations=transformations,
metadata_project=metadata_project,
metadata_schema=metadata_schema,
),
)
df._reader = self
set_api_call_source(df, "DataFrameReader.csv")
# AST.
if _emit_ast:
stmt = self._session._ast_batch.assign()
ast = with_src_position(stmt.expr.sp_read_csv, stmt)
ast.path = path
ast.reader.CopyFrom(self._ast)
df._ast_id = stmt.var_id.bitfield1
return df
@publicapi
def json(self, path: str, _emit_ast: bool = True) -> DataFrame:
"""Specify the path of the JSON file(s) to load.
Args:
path: The stage location of a JSON file, or a stage location that has JSON files.
Returns:
a :class:`DataFrame` that is set up to load data from the specified JSON file(s) in a Snowflake stage.
"""
# infer_schema is set to false by default for JSON
if "INFER_SCHEMA" not in self._cur_options:
self._cur_options["INFER_SCHEMA"] = False
df = self._read_semi_structured_file(path, "JSON")
# AST.
if _emit_ast:
stmt = self._session._ast_batch.assign()
ast = with_src_position(stmt.expr.sp_read_json, stmt)
ast.path = path
ast.reader.CopyFrom(self._ast)
df._ast_id = stmt.var_id.bitfield1
return df
@publicapi
def avro(self, path: str, _emit_ast: bool = True) -> DataFrame:
"""Specify the path of the AVRO file(s) to load.
Args:
path: The stage location of an AVRO file, or a stage location that has AVRO files.
Note:
When using :meth:`DataFrame.select`, quote the column names to select the desired columns.
This is needed because converting from AVRO to `class`:`DataFrame` does not capitalize the
column names from the original columns and a :meth:`DataFrame.select` without quote looks for
capitalized column names.
Returns:
a :class:`DataFrame` that is set up to load data from the specified AVRO file(s) in a Snowflake stage.
"""
df = self._read_semi_structured_file(path, "AVRO")
# AST.
if _emit_ast:
stmt = self._session._ast_batch.assign()
ast = with_src_position(stmt.expr.sp_read_avro, stmt)
ast.path = path
ast.reader.CopyFrom(self._ast)
df._ast_id = stmt.var_id.bitfield1
return df
@publicapi
def parquet(self, path: str, _emit_ast: bool = True) -> DataFrame:
"""Specify the path of the PARQUET file(s) to load.
Args:
path: The stage location of a PARQUET file, or a stage location that has PARQUET files.
Note:
When using :meth:`DataFrame.select`, quote the column names to select the desired columns.
This is needed because converting from PARQUET to `class`:`DataFrame` does not capitalize the
column names from the original columns and a :meth:`DataFrame.select` without quote looks for
capitalized column names.
Returns:
a :class:`DataFrame` that is set up to load data from the specified PARQUET file(s) in a Snowflake stage.
"""
df = self._read_semi_structured_file(path, "PARQUET")
# AST.
if _emit_ast:
stmt = self._session._ast_batch.assign()
ast = with_src_position(stmt.expr.sp_read_parquet, stmt)
ast.path = path
ast.reader.CopyFrom(self._ast)
df._ast_id = stmt.var_id.bitfield1
return df
@publicapi
def orc(self, path: str, _emit_ast: bool = True) -> DataFrame:
"""Specify the path of the ORC file(s) to load.
Args:
path: The stage location of a ORC file, or a stage location that has ORC files.
Note:
When using :meth:`DataFrame.select`, quote the column names to select the desired columns.
This is needed because converting from ORC to `class`:`DataFrame` does not capitalize the
column names from the original columns and a :meth:`DataFrame.select` without quote looks for
capitalized column names.
Returns:
a :class:`DataFrame` that is set up to load data from the specified ORC file(s) in a Snowflake stage.
"""
df = self._read_semi_structured_file(path, "ORC")
# AST.
if _emit_ast:
stmt = self._session._ast_batch.assign()
ast = with_src_position(stmt.expr.sp_read_orc, stmt)
ast.path = path
ast.reader.CopyFrom(self._ast)
df._ast_id = stmt.var_id.bitfield1
return df
@publicapi
def xml(self, path: str, _emit_ast: bool = True) -> DataFrame:
"""Specify the path of the XML file(s) to load.
Args:
path: The stage location of an XML file, or a stage location that has XML files.
Returns:
a :class:`DataFrame` that is set up to load data from the specified XML file(s) in a Snowflake stage.
"""
df = self._read_semi_structured_file(path, "XML")
# AST.
if _emit_ast:
stmt = self._session._ast_batch.assign()
ast = with_src_position(stmt.expr.sp_read_xml, stmt)
ast.path = path
ast.reader.CopyFrom(self._ast)
df._ast_id = stmt.var_id.bitfield1
return df
@publicapi
def option(self, key: str, value: Any, _emit_ast: bool = True) -> "DataFrameReader":
"""Sets the specified option in the DataFrameReader.
Use this method to configure any
`format-specific options <https://docs.snowflake.com/en/sql-reference/sql/create-file-format.html#format-type-options-formattypeoptions>`_
and
`copy options <https://docs.snowflake.com/en/sql-reference/sql/copy-into-table.html#copy-options-copyoptions>`_.
(Note that although specifying copy options can make error handling more robust during the
reading process, it may have an effect on performance.)
Args:
key: Name of the option (e.g. ``compression``, ``skip_header``, etc.).
value: Value of the option.
"""
# AST.
if _emit_ast:
reader = proto.SpDataframeReader()
ast = with_src_position(reader.sp_dataframe_reader_option)
ast.reader.CopyFrom(self._ast)
ast.key = key
build_expr_from_python_val(ast.value, value)
self._ast = reader
aliased_key = get_aliased_option_name(key, READER_OPTIONS_ALIAS_MAP)
self._cur_options[aliased_key] = value
return self
@publicapi
def options(
self, configs: Optional[Dict] = None, _emit_ast: bool = True, **kwargs
) -> "DataFrameReader":
"""Sets multiple specified options in the DataFrameReader.
This method is the same as the :meth:`option` except that you can set multiple options in one call.
Args:
configs: Dictionary of the names of options (e.g. ``compression``,
``skip_header``, etc.) and their corresponding values.
"""
if configs and kwargs:
raise ValueError(
"Cannot set options with both a dictionary and keyword arguments. Please use one or the other."
)
if configs is None:
if not kwargs:
raise ValueError("No options were provided")
configs = kwargs
# AST.
if _emit_ast:
reader = proto.SpDataframeReader()
ast = with_src_position(reader.sp_dataframe_reader_options)
ast.reader.CopyFrom(self._ast)
for k, v in configs.items():
t = ast.configs.add()
t._1 = k
build_expr_from_python_val(t._2, v)
self._ast = reader
for k, v in configs.items():
self.option(k, v, _emit_ast=False)
return self
def _infer_schema_for_file_format(
self, path: str, format: str
) -> Tuple[List, List, List, Exception]:
format_type_options, _ = get_copy_into_table_options(self._cur_options)
temp_file_format_name = self._session.get_fully_qualified_name_if_possible(
random_name_for_temp_object(TempObjectType.FILE_FORMAT)
)
drop_tmp_file_format_if_exists_query: Optional[str] = None
use_temp_file_format = "FORMAT_NAME" not in self._cur_options
file_format_name = self._cur_options.get("FORMAT_NAME", temp_file_format_name)
infer_schema_options = self._cur_options.get("INFER_SCHEMA_OPTIONS", None)
infer_schema_query = infer_schema_statement(
path, file_format_name, infer_schema_options
)
try:
if use_temp_file_format:
self._session._conn.run_query(
create_file_format_statement(
file_format_name,
format,
format_type_options,
temp=True,
if_not_exist=True,
use_scoped_temp_objects=self._session._use_scoped_temp_objects,
is_generated=True,
),
is_ddl_on_temp_object=True,
)
drop_tmp_file_format_if_exists_query = (
drop_file_format_if_exists_statement(file_format_name)
)
# SNOW-1628625: Schema inference should be done lazily
results = self._session._conn.run_query(infer_schema_query)["data"]
if len(results) == 0:
raise FileNotFoundError(
f"Given path: '{path}' could not be found or is empty."
)
new_schema = []
schema_to_cast = []
transformations: List["snowflake.snowpark.column.Column"] = []
read_file_transformations = None
for r in results:
# Columns for r [column_name, type, nullable, expression, filenames]
name = quote_name_without_upper_casing(r[0])
# Parse the type returned by infer_schema command to
# pass to determine datatype for schema
data_type_parts = r[1].split("(")
parts_length = len(data_type_parts)
if parts_length == 1:
data_type = r[1]
precision = 0
scale = 0
else:
data_type = data_type_parts[0]
precision = int(data_type_parts[1].split(",")[0])
scale = int(data_type_parts[1].split(",")[1][:-1])
new_schema.append(
Attribute(
name,
convert_sf_to_sp_type(
data_type,
precision,
scale,
0,
self._session._conn.max_string_size,
),
r[2],
)
)
identifier = f"$1:{name}::{r[1]}" if format != "CSV" else r[3]
schema_to_cast.append((identifier, r[0]))
transformations.append(sql_expr(identifier))
self._user_schema = StructType._from_attributes(new_schema)
# If the user sets transformations, we should not override this
self._infer_schema_transformations = transformations
self._infer_schema_target_columns = self._user_schema.names
read_file_transformations = [t._expression.sql for t in transformations]
except Exception as e:
return None, None, None, e
finally:
# Clean up the file format we created
if drop_tmp_file_format_if_exists_query is not None:
self._session._conn.run_query(
drop_tmp_file_format_if_exists_query, is_ddl_on_temp_object=True
)
return new_schema, schema_to_cast, read_file_transformations, None
def _read_semi_structured_file(self, path: str, format: str) -> DataFrame:
if isinstance(self._session._conn, MockServerConnection):
if self._session._conn.is_closed():
raise SnowparkSessionException(
"Cannot perform this operation because the session has been closed.",
error_code="1404",
)
if format not in LOCAL_TESTING_SUPPORTED_FILE_FORMAT:
self._session._conn.log_not_supported_error(
external_feature_name=f"Read semi structured {format} file",
internal_feature_name="DataFrameReader._read_semi_structured_file",
parameters_info={"format": str(format)},
raise_error=NotImplementedError,
)
if self._user_schema:
raise ValueError(f"Read {format} does not support user schema")
path = _validate_stage_path(path)
self._file_path = path
self._file_type = format
schema = [Attribute('"$1"', VariantType())]
read_file_transformations = None
schema_to_cast = None
if self._infer_schema:
(
new_schema,
schema_to_cast,
read_file_transformations,
_, # we don't check for error in case of infer schema failures. We use $1, Variant type
) = self._infer_schema_for_file_format(path, format)
if new_schema:
schema = new_schema
metadata_project, metadata_schema = self._get_metadata_project_and_schema()
if self._session.sql_simplifier_enabled:
df = DataFrame(
self._session,
self._session._analyzer.create_select_statement(
from_=self._session._analyzer.create_select_snowflake_plan(
self._session._plan_builder.read_file(
path,
format,
self._cur_options,
schema,
schema_to_cast=schema_to_cast,
transformations=read_file_transformations,
metadata_project=metadata_project,
metadata_schema=metadata_schema,
),
analyzer=self._session._analyzer,
),
analyzer=self._session._analyzer,
),