snowpark-connect 0.28.1__py3-none-any.whl → 0.29.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of snowpark-connect might be problematic. Click here for more details.
- snowflake/snowpark_connect/config.py +11 -2
- snowflake/snowpark_connect/expression/map_unresolved_function.py +172 -210
- snowflake/snowpark_connect/relation/io_utils.py +21 -1
- snowflake/snowpark_connect/relation/map_extension.py +21 -4
- snowflake/snowpark_connect/relation/map_map_partitions.py +7 -8
- snowflake/snowpark_connect/relation/map_relation.py +1 -3
- snowflake/snowpark_connect/relation/read/map_read.py +22 -3
- snowflake/snowpark_connect/relation/read/map_read_csv.py +105 -26
- snowflake/snowpark_connect/relation/read/map_read_json.py +45 -34
- snowflake/snowpark_connect/relation/read/map_read_text.py +6 -1
- snowflake/snowpark_connect/relation/stage_locator.py +85 -53
- snowflake/snowpark_connect/relation/write/map_write.py +38 -4
- snowflake/snowpark_connect/server.py +18 -13
- snowflake/snowpark_connect/utils/context.py +0 -14
- snowflake/snowpark_connect/utils/io_utils.py +36 -0
- snowflake/snowpark_connect/utils/session.py +3 -0
- snowflake/snowpark_connect/utils/udf_cache.py +37 -7
- snowflake/snowpark_connect/version.py +1 -1
- {snowpark_connect-0.28.1.dist-info → snowpark_connect-0.29.0.dist-info}/METADATA +3 -2
- {snowpark_connect-0.28.1.dist-info → snowpark_connect-0.29.0.dist-info}/RECORD +28 -28
- {snowpark_connect-0.28.1.data → snowpark_connect-0.29.0.data}/scripts/snowpark-connect +0 -0
- {snowpark_connect-0.28.1.data → snowpark_connect-0.29.0.data}/scripts/snowpark-session +0 -0
- {snowpark_connect-0.28.1.data → snowpark_connect-0.29.0.data}/scripts/snowpark-submit +0 -0
- {snowpark_connect-0.28.1.dist-info → snowpark_connect-0.29.0.dist-info}/WHEEL +0 -0
- {snowpark_connect-0.28.1.dist-info → snowpark_connect-0.29.0.dist-info}/licenses/LICENSE-binary +0 -0
- {snowpark_connect-0.28.1.dist-info → snowpark_connect-0.29.0.dist-info}/licenses/LICENSE.txt +0 -0
- {snowpark_connect-0.28.1.dist-info → snowpark_connect-0.29.0.dist-info}/licenses/NOTICE-binary +0 -0
- {snowpark_connect-0.28.1.dist-info → snowpark_connect-0.29.0.dist-info}/top_level.txt +0 -0
|
@@ -345,7 +345,7 @@ def map_aggregate(
|
|
|
345
345
|
return new_names[0], snowpark_column
|
|
346
346
|
|
|
347
347
|
raw_groupings: list[tuple[str, TypedColumn]] = []
|
|
348
|
-
raw_aggregations: list[tuple[str, TypedColumn]] = []
|
|
348
|
+
raw_aggregations: list[tuple[str, TypedColumn, list[str]]] = []
|
|
349
349
|
|
|
350
350
|
if not is_group_by_all:
|
|
351
351
|
raw_groupings = [_map_column(exp) for exp in aggregate.grouping_expressions]
|
|
@@ -375,10 +375,21 @@ def map_aggregate(
|
|
|
375
375
|
# Note: We don't clear the map here to preserve any parent context aliases
|
|
376
376
|
from snowflake.snowpark_connect.utils.context import register_lca_alias
|
|
377
377
|
|
|
378
|
+
# If it's an unresolved attribute when its in aggregate.aggregate_expressions, we know it came from the parent map straight away
|
|
379
|
+
# in this case, we should see if the parent map has a qualifier for it and propagate that here, in case the order by references it in
|
|
380
|
+
# a qualified way later.
|
|
378
381
|
agg_count = get_sql_aggregate_function_count()
|
|
379
382
|
for exp in aggregate.aggregate_expressions:
|
|
380
383
|
col = _map_column(exp)
|
|
381
|
-
|
|
384
|
+
if exp.WhichOneof("expr_type") == "unresolved_attribute":
|
|
385
|
+
spark_name = col[0]
|
|
386
|
+
qualifiers = input_container.column_map.get_qualifier_for_spark_column(
|
|
387
|
+
spark_name
|
|
388
|
+
)
|
|
389
|
+
else:
|
|
390
|
+
qualifiers = []
|
|
391
|
+
|
|
392
|
+
raw_aggregations.append((col[0], col[1], qualifiers))
|
|
382
393
|
|
|
383
394
|
# If this is an alias, register it in the LCA map for subsequent expressions
|
|
384
395
|
if (
|
|
@@ -409,18 +420,20 @@ def map_aggregate(
|
|
|
409
420
|
spark_columns: list[str] = []
|
|
410
421
|
snowpark_columns: list[str] = []
|
|
411
422
|
snowpark_column_types: list[snowpark_types.DataType] = []
|
|
423
|
+
all_qualifiers: list[list[str]] = []
|
|
412
424
|
|
|
413
425
|
# Use grouping columns directly without aliases
|
|
414
426
|
groupings = [col.col for _, col in raw_groupings]
|
|
415
427
|
|
|
416
428
|
# Create aliases only for aggregation columns
|
|
417
429
|
aggregations = []
|
|
418
|
-
for i, (spark_name, snowpark_column) in enumerate(raw_aggregations):
|
|
430
|
+
for i, (spark_name, snowpark_column, qualifiers) in enumerate(raw_aggregations):
|
|
419
431
|
alias = make_column_names_snowpark_compatible([spark_name], plan_id, i)[0]
|
|
420
432
|
|
|
421
433
|
spark_columns.append(spark_name)
|
|
422
434
|
snowpark_columns.append(alias)
|
|
423
435
|
snowpark_column_types.append(snowpark_column.typ)
|
|
436
|
+
all_qualifiers.append(qualifiers)
|
|
424
437
|
|
|
425
438
|
aggregations.append(snowpark_column.col.alias(alias))
|
|
426
439
|
|
|
@@ -483,6 +496,7 @@ def map_aggregate(
|
|
|
483
496
|
spark_column_names=spark_columns,
|
|
484
497
|
snowpark_column_names=snowpark_columns,
|
|
485
498
|
snowpark_column_types=snowpark_column_types,
|
|
499
|
+
column_qualifiers=all_qualifiers,
|
|
486
500
|
).column_map
|
|
487
501
|
|
|
488
502
|
# Create hybrid column map that can resolve both input and aggregate contexts
|
|
@@ -494,7 +508,9 @@ def map_aggregate(
|
|
|
494
508
|
aggregate_expressions=list(aggregate.aggregate_expressions),
|
|
495
509
|
grouping_expressions=list(aggregate.grouping_expressions),
|
|
496
510
|
spark_columns=spark_columns,
|
|
497
|
-
raw_aggregations=
|
|
511
|
+
raw_aggregations=[
|
|
512
|
+
(spark_name, col) for spark_name, col, _ in raw_aggregations
|
|
513
|
+
],
|
|
498
514
|
)
|
|
499
515
|
|
|
500
516
|
# Map the HAVING condition using hybrid resolution
|
|
@@ -515,4 +531,5 @@ def map_aggregate(
|
|
|
515
531
|
snowpark_column_names=snowpark_columns,
|
|
516
532
|
snowpark_column_types=snowpark_column_types,
|
|
517
533
|
parent_column_name_map=input_df._column_map,
|
|
534
|
+
column_qualifiers=all_qualifiers,
|
|
518
535
|
)
|
|
@@ -12,7 +12,6 @@ from snowflake.snowpark_connect.constants import MAP_IN_ARROW_EVAL_TYPE
|
|
|
12
12
|
from snowflake.snowpark_connect.dataframe_container import DataFrameContainer
|
|
13
13
|
from snowflake.snowpark_connect.relation.map_relation import map_relation
|
|
14
14
|
from snowflake.snowpark_connect.type_mapping import proto_to_snowpark_type
|
|
15
|
-
from snowflake.snowpark_connect.utils.context import map_partitions_depth
|
|
16
15
|
from snowflake.snowpark_connect.utils.pandas_udtf_utils import (
|
|
17
16
|
create_pandas_udtf,
|
|
18
17
|
create_pandas_udtf_with_arrow,
|
|
@@ -53,18 +52,18 @@ def _call_udtf(
|
|
|
53
52
|
).cast("int"),
|
|
54
53
|
)
|
|
55
54
|
|
|
56
|
-
udtf_columns = input_df.columns + [
|
|
55
|
+
udtf_columns = [f"snowflake_jtf_{column}" for column in input_df.columns] + [
|
|
56
|
+
"_DUMMY_PARTITION_KEY"
|
|
57
|
+
]
|
|
57
58
|
|
|
58
59
|
tfc = snowpark_fn.call_table_function(udtf_name, *udtf_columns).over(
|
|
59
60
|
partition_by=[snowpark_fn.col("_DUMMY_PARTITION_KEY")]
|
|
60
61
|
)
|
|
61
62
|
|
|
62
|
-
#
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
else:
|
|
67
|
-
result_df_with_dummy = input_df_with_dummy.select(tfc)
|
|
63
|
+
# Overwrite the input_df columns to prevent name conflicts with UDTF output columns
|
|
64
|
+
result_df_with_dummy = input_df_with_dummy.to_df(udtf_columns).join_table_function(
|
|
65
|
+
tfc
|
|
66
|
+
)
|
|
68
67
|
|
|
69
68
|
output_cols = [field.name for field in return_type.fields]
|
|
70
69
|
|
|
@@ -16,7 +16,6 @@ from snowflake.snowpark_connect.utils.context import (
|
|
|
16
16
|
get_plan_id_map,
|
|
17
17
|
get_session_id,
|
|
18
18
|
not_resolving_fun_args,
|
|
19
|
-
push_map_partitions,
|
|
20
19
|
push_operation_scope,
|
|
21
20
|
set_is_aggregate_function,
|
|
22
21
|
set_plan_id_map,
|
|
@@ -185,8 +184,7 @@ def map_relation(
|
|
|
185
184
|
)
|
|
186
185
|
return cached_df
|
|
187
186
|
case "map_partitions":
|
|
188
|
-
|
|
189
|
-
result = map_map_partitions.map_map_partitions(rel)
|
|
187
|
+
result = map_map_partitions.map_map_partitions(rel)
|
|
190
188
|
case "offset":
|
|
191
189
|
result = map_row_ops.map_offset(rel)
|
|
192
190
|
case "project":
|
|
@@ -46,6 +46,9 @@ def map_read(
|
|
|
46
46
|
|
|
47
47
|
Currently, the supported read formats are `csv`, `json` and `parquet`.
|
|
48
48
|
"""
|
|
49
|
+
|
|
50
|
+
materialize_df = True
|
|
51
|
+
|
|
49
52
|
match rel.read.WhichOneof("read_type"):
|
|
50
53
|
case "named_table":
|
|
51
54
|
return map_read_table_or_file(rel)
|
|
@@ -99,6 +102,10 @@ def map_read(
|
|
|
99
102
|
for path in rel.read.data_source.paths
|
|
100
103
|
]
|
|
101
104
|
|
|
105
|
+
# JSON already materializes the table internally
|
|
106
|
+
if read_format == "json":
|
|
107
|
+
materialize_df = False
|
|
108
|
+
|
|
102
109
|
result = _read_file(
|
|
103
110
|
clean_source_paths, options, read_format, rel, schema, session
|
|
104
111
|
)
|
|
@@ -159,7 +166,9 @@ def map_read(
|
|
|
159
166
|
raise SnowparkConnectNotImplementedError(f"Unsupported read type: {other}")
|
|
160
167
|
|
|
161
168
|
return df_cache_map_put_if_absent(
|
|
162
|
-
(get_session_id(), rel.common.plan_id),
|
|
169
|
+
(get_session_id(), rel.common.plan_id),
|
|
170
|
+
lambda: result,
|
|
171
|
+
materialize=materialize_df,
|
|
163
172
|
)
|
|
164
173
|
|
|
165
174
|
|
|
@@ -205,6 +214,15 @@ def _get_supported_read_file_format(unparsed_identifier: str) -> str | None:
|
|
|
205
214
|
return None
|
|
206
215
|
|
|
207
216
|
|
|
217
|
+
def _quote_stage_path(stage_path: str) -> str:
|
|
218
|
+
"""
|
|
219
|
+
Quote stage paths to escape any special characters.
|
|
220
|
+
"""
|
|
221
|
+
if stage_path.startswith("@"):
|
|
222
|
+
return f"'{stage_path}'"
|
|
223
|
+
return stage_path
|
|
224
|
+
|
|
225
|
+
|
|
208
226
|
def _read_file(
|
|
209
227
|
clean_source_paths: list[str],
|
|
210
228
|
options: dict,
|
|
@@ -218,6 +236,7 @@ def _read_file(
|
|
|
218
236
|
session,
|
|
219
237
|
)
|
|
220
238
|
upload_files_if_needed(paths, clean_source_paths, session, read_format)
|
|
239
|
+
paths = [_quote_stage_path(path) for path in paths]
|
|
221
240
|
match read_format:
|
|
222
241
|
case "csv":
|
|
223
242
|
from snowflake.snowpark_connect.relation.read.map_read_csv import (
|
|
@@ -285,8 +304,8 @@ def upload_files_if_needed(
|
|
|
285
304
|
|
|
286
305
|
def _upload_dir(target: str, source: str) -> None:
|
|
287
306
|
# overwrite=True will not remove all stale files in the target prefix
|
|
288
|
-
|
|
289
|
-
remove_command = f"REMOVE {target}/"
|
|
307
|
+
# Quote the target path to allow special characters.
|
|
308
|
+
remove_command = f"REMOVE '{target}/'"
|
|
290
309
|
assert (
|
|
291
310
|
"//" not in remove_command
|
|
292
311
|
), f"Remove command {remove_command} contains double slash"
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
#
|
|
4
4
|
|
|
5
5
|
import copy
|
|
6
|
+
from typing import Any
|
|
6
7
|
|
|
7
8
|
import pyspark.sql.connect.proto.relations_pb2 as relation_proto
|
|
8
9
|
|
|
@@ -16,6 +17,7 @@ from snowflake.snowpark_connect.relation.read.utils import (
|
|
|
16
17
|
get_spark_column_names_from_snowpark_columns,
|
|
17
18
|
rename_columns_as_snowflake_standard,
|
|
18
19
|
)
|
|
20
|
+
from snowflake.snowpark_connect.utils.io_utils import cached_file_format
|
|
19
21
|
from snowflake.snowpark_connect.utils.telemetry import (
|
|
20
22
|
SnowparkConnectNotImplementedError,
|
|
21
23
|
)
|
|
@@ -42,21 +44,34 @@ def map_read_csv(
|
|
|
42
44
|
)
|
|
43
45
|
else:
|
|
44
46
|
snowpark_options = options.convert_to_snowpark_args()
|
|
47
|
+
parse_header = snowpark_options.get("PARSE_HEADER", False)
|
|
48
|
+
file_format_options = _parse_csv_snowpark_options(snowpark_options)
|
|
49
|
+
file_format = cached_file_format(session, "csv", file_format_options)
|
|
50
|
+
|
|
51
|
+
snowpark_read_options = dict()
|
|
52
|
+
snowpark_read_options["FORMAT_NAME"] = file_format
|
|
53
|
+
snowpark_read_options["ENFORCE_EXISTING_FILE_FORMAT"] = True
|
|
54
|
+
snowpark_read_options["INFER_SCHEMA"] = snowpark_options.get(
|
|
55
|
+
"INFER_SCHEMA", False
|
|
56
|
+
)
|
|
57
|
+
snowpark_read_options["PATTERN"] = snowpark_options.get("PATTERN", None)
|
|
58
|
+
|
|
45
59
|
raw_options = rel.read.data_source.options
|
|
46
60
|
if schema is None or (
|
|
47
|
-
|
|
48
|
-
and raw_options.get("enforceSchema", "True").lower() == "false"
|
|
61
|
+
parse_header and raw_options.get("enforceSchema", "True").lower() == "false"
|
|
49
62
|
): # Schema has to equals to header's format
|
|
50
|
-
reader = session.read.options(
|
|
63
|
+
reader = session.read.options(snowpark_read_options)
|
|
51
64
|
else:
|
|
52
|
-
reader = session.read.options(
|
|
65
|
+
reader = session.read.options(snowpark_read_options).schema(schema)
|
|
53
66
|
df = read_data(
|
|
54
67
|
reader,
|
|
55
68
|
schema,
|
|
56
69
|
session,
|
|
57
70
|
paths[0],
|
|
58
|
-
|
|
71
|
+
file_format_options,
|
|
72
|
+
snowpark_read_options,
|
|
59
73
|
raw_options,
|
|
74
|
+
parse_header,
|
|
60
75
|
)
|
|
61
76
|
if len(paths) > 1:
|
|
62
77
|
# TODO: figure out if this is what Spark does.
|
|
@@ -81,15 +96,65 @@ def map_read_csv(
|
|
|
81
96
|
)
|
|
82
97
|
|
|
83
98
|
|
|
99
|
+
_csv_file_format_allowed_options = {
|
|
100
|
+
"COMPRESSION",
|
|
101
|
+
"RECORD_DELIMITER",
|
|
102
|
+
"FIELD_DELIMITER",
|
|
103
|
+
"MULTI_LINE",
|
|
104
|
+
"FILE_EXTENSION",
|
|
105
|
+
"PARSE_HEADER",
|
|
106
|
+
"SKIP_HEADER",
|
|
107
|
+
"SKIP_BLANK_LINES",
|
|
108
|
+
"DATE_FORMAT",
|
|
109
|
+
"TIME_FORMAT",
|
|
110
|
+
"TIMESTAMP_FORMAT",
|
|
111
|
+
"BINARY_FORMAT",
|
|
112
|
+
"ESCAPE",
|
|
113
|
+
"ESCAPE_UNENCLOSED_FIELD",
|
|
114
|
+
"TRIM_SPACE",
|
|
115
|
+
"FIELD_OPTIONALLY_ENCLOSED_BY",
|
|
116
|
+
"NULL_IF",
|
|
117
|
+
"ERROR_ON_COLUMN_COUNT_MISMATCH",
|
|
118
|
+
"REPLACE_INVALID_CHARACTERS",
|
|
119
|
+
"EMPTY_FIELD_AS_NULL",
|
|
120
|
+
"SKIP_BYTE_ORDER_MARK",
|
|
121
|
+
"ENCODING",
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _parse_csv_snowpark_options(snowpark_options: dict[str, Any]) -> dict[str, Any]:
|
|
126
|
+
file_format_options = dict()
|
|
127
|
+
for key, value in snowpark_options.items():
|
|
128
|
+
upper_key = key.upper()
|
|
129
|
+
if upper_key in _csv_file_format_allowed_options:
|
|
130
|
+
file_format_options[upper_key] = value
|
|
131
|
+
|
|
132
|
+
# This option has to be removed, because we cannot use at the same time predefined file format and parse_header option
|
|
133
|
+
# Such combination causes snowpark to raise SQL compilation error: Invalid file format "PARSE_HEADER" is only allowed for CSV INFER_SCHEMA and MATCH_BY_COLUMN_NAME
|
|
134
|
+
parse_header = file_format_options.get("PARSE_HEADER", False)
|
|
135
|
+
if parse_header:
|
|
136
|
+
file_format_options["SKIP_HEADER"] = 1
|
|
137
|
+
del file_format_options["PARSE_HEADER"]
|
|
138
|
+
|
|
139
|
+
return file_format_options
|
|
140
|
+
|
|
141
|
+
|
|
84
142
|
def get_header_names(
|
|
85
143
|
session: snowpark.Session,
|
|
86
144
|
path: list[str],
|
|
87
|
-
|
|
145
|
+
file_format_options: dict,
|
|
146
|
+
snowpark_read_options: dict,
|
|
88
147
|
) -> list[str]:
|
|
89
|
-
|
|
90
|
-
|
|
148
|
+
no_header_file_format_options = copy.copy(file_format_options)
|
|
149
|
+
no_header_file_format_options["PARSE_HEADER"] = False
|
|
150
|
+
no_header_file_format_options.pop("SKIP_HEADER", None)
|
|
151
|
+
|
|
152
|
+
file_format = cached_file_format(session, "csv", no_header_file_format_options)
|
|
153
|
+
no_header_snowpark_read_options = copy.copy(snowpark_read_options)
|
|
154
|
+
no_header_snowpark_read_options["FORMAT_NAME"] = file_format
|
|
155
|
+
no_header_snowpark_read_options.pop("INFER_SCHEMA", None)
|
|
91
156
|
|
|
92
|
-
header_df = session.read.options(
|
|
157
|
+
header_df = session.read.options(no_header_snowpark_read_options).csv(path).limit(1)
|
|
93
158
|
header_data = header_df.collect()[0]
|
|
94
159
|
return [
|
|
95
160
|
f'"{header_data[i]}"'
|
|
@@ -103,8 +168,10 @@ def read_data(
|
|
|
103
168
|
schema: snowpark.types.StructType | None,
|
|
104
169
|
session: snowpark.Session,
|
|
105
170
|
path: list[str],
|
|
106
|
-
|
|
171
|
+
file_format_options: dict,
|
|
172
|
+
snowpark_read_options: dict,
|
|
107
173
|
raw_options: dict,
|
|
174
|
+
parse_header: bool,
|
|
108
175
|
) -> snowpark.DataFrame:
|
|
109
176
|
df = reader.csv(path)
|
|
110
177
|
filename = path.strip("/").split("/")[-1]
|
|
@@ -120,23 +187,35 @@ def read_data(
|
|
|
120
187
|
raise Exception("CSV header does not conform to the schema")
|
|
121
188
|
return df
|
|
122
189
|
|
|
123
|
-
headers = get_header_names(
|
|
124
|
-
|
|
190
|
+
headers = get_header_names(
|
|
191
|
+
session, path, file_format_options, snowpark_read_options
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
df_schema_fields = df.schema.fields
|
|
195
|
+
if len(headers) == len(df_schema_fields) and parse_header:
|
|
196
|
+
return df.select(
|
|
197
|
+
[
|
|
198
|
+
snowpark_fn.col(df_schema_fields[i].name).alias(headers[i])
|
|
199
|
+
for i in range(len(headers))
|
|
200
|
+
]
|
|
201
|
+
)
|
|
125
202
|
# Handle mismatch in column count between header and data
|
|
126
|
-
|
|
127
|
-
len(
|
|
128
|
-
and
|
|
129
|
-
and
|
|
130
|
-
and len(headers) != len(
|
|
203
|
+
elif (
|
|
204
|
+
len(df_schema_fields) == 1
|
|
205
|
+
and df_schema_fields[0].name.upper() == "C1"
|
|
206
|
+
and parse_header
|
|
207
|
+
and len(headers) != len(df_schema_fields)
|
|
131
208
|
):
|
|
132
|
-
df = (
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
209
|
+
df = reader.schema(
|
|
210
|
+
StructType([StructField(h, StringType(), True) for h in headers])
|
|
211
|
+
).csv(path)
|
|
212
|
+
elif not parse_header and len(headers) != len(df_schema_fields):
|
|
213
|
+
return df.select([df_schema_fields[i].name for i in range(len(headers))])
|
|
214
|
+
elif parse_header and len(headers) != len(df_schema_fields):
|
|
215
|
+
return df.select(
|
|
216
|
+
[
|
|
217
|
+
snowpark_fn.col(df_schema_fields[i].name).alias(headers[i])
|
|
218
|
+
for i in range(len(headers))
|
|
219
|
+
]
|
|
136
220
|
)
|
|
137
|
-
elif snowpark_options.get("PARSE_HEADER") is False and len(headers) != len(
|
|
138
|
-
df.schema.fields
|
|
139
|
-
):
|
|
140
|
-
return df.select([df.schema.fields[i].name for i in range(len(headers))])
|
|
141
|
-
|
|
142
221
|
return df
|
|
@@ -2,9 +2,12 @@
|
|
|
2
2
|
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
|
|
3
3
|
#
|
|
4
4
|
|
|
5
|
+
import concurrent.futures
|
|
5
6
|
import copy
|
|
6
7
|
import json
|
|
8
|
+
import os
|
|
7
9
|
import typing
|
|
10
|
+
import uuid
|
|
8
11
|
from contextlib import suppress
|
|
9
12
|
from datetime import datetime
|
|
10
13
|
|
|
@@ -253,20 +256,20 @@ def merge_row_schema(
|
|
|
253
256
|
return schema
|
|
254
257
|
|
|
255
258
|
|
|
256
|
-
def
|
|
257
|
-
result_df: snowpark.DataFrame,
|
|
258
|
-
data: typing.List[Row],
|
|
259
|
-
schema: StructType,
|
|
259
|
+
def insert_data_chunk(
|
|
260
260
|
session: snowpark.Session,
|
|
261
|
-
|
|
262
|
-
|
|
261
|
+
data: list[Row],
|
|
262
|
+
schema: StructType,
|
|
263
|
+
table_name: str,
|
|
264
|
+
) -> None:
|
|
265
|
+
df = session.create_dataframe(
|
|
263
266
|
data=data,
|
|
264
267
|
schema=schema,
|
|
265
268
|
)
|
|
266
|
-
if result_df is None:
|
|
267
|
-
return current_df
|
|
268
269
|
|
|
269
|
-
|
|
270
|
+
df.write.mode("append").save_as_table(
|
|
271
|
+
table_name, table_type="temp", table_exists=True
|
|
272
|
+
)
|
|
270
273
|
|
|
271
274
|
|
|
272
275
|
def construct_dataframe_by_schema(
|
|
@@ -276,39 +279,47 @@ def construct_dataframe_by_schema(
|
|
|
276
279
|
snowpark_options: dict,
|
|
277
280
|
batch_size: int = 1000,
|
|
278
281
|
) -> snowpark.DataFrame:
|
|
279
|
-
|
|
282
|
+
table_name = "__sas_json_read_temp_" + uuid.uuid4().hex
|
|
283
|
+
|
|
284
|
+
# We can have more workers than CPU count, this is an IO-intensive task
|
|
285
|
+
max_workers = min(16, os.cpu_count() * 2)
|
|
280
286
|
|
|
281
287
|
current_data = []
|
|
282
288
|
progress = 0
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
289
|
+
|
|
290
|
+
# Initialize the temp table
|
|
291
|
+
session.create_dataframe([], schema=schema).write.mode("append").save_as_table(
|
|
292
|
+
table_name, table_type="temp", table_exists=False
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as exc:
|
|
296
|
+
for row in rows:
|
|
297
|
+
current_data.append(construct_row_by_schema(row, schema, snowpark_options))
|
|
298
|
+
if len(current_data) >= batch_size:
|
|
299
|
+
progress += len(current_data)
|
|
300
|
+
exc.submit(
|
|
301
|
+
insert_data_chunk,
|
|
302
|
+
session,
|
|
303
|
+
copy.deepcopy(current_data),
|
|
304
|
+
schema,
|
|
305
|
+
table_name,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
logger.info(f"JSON reader: finished processing {progress} rows")
|
|
309
|
+
current_data.clear()
|
|
310
|
+
|
|
311
|
+
if len(current_data) > 0:
|
|
286
312
|
progress += len(current_data)
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
current_data,
|
|
290
|
-
schema,
|
|
313
|
+
exc.submit(
|
|
314
|
+
insert_data_chunk,
|
|
291
315
|
session,
|
|
316
|
+
copy.deepcopy(current_data),
|
|
317
|
+
schema,
|
|
318
|
+
table_name,
|
|
292
319
|
)
|
|
293
|
-
|
|
294
320
|
logger.info(f"JSON reader: finished processing {progress} rows")
|
|
295
|
-
current_data = []
|
|
296
|
-
|
|
297
|
-
if len(current_data) > 0:
|
|
298
|
-
progress += len(current_data)
|
|
299
|
-
result = union_data_into_df(
|
|
300
|
-
result,
|
|
301
|
-
current_data,
|
|
302
|
-
schema,
|
|
303
|
-
session,
|
|
304
|
-
)
|
|
305
|
-
|
|
306
|
-
logger.info(f"JSON reader: finished processing {progress} rows")
|
|
307
|
-
current_data = []
|
|
308
321
|
|
|
309
|
-
|
|
310
|
-
raise ValueError("Dataframe cannot be empty")
|
|
311
|
-
return result
|
|
322
|
+
return session.table(table_name)
|
|
312
323
|
|
|
313
324
|
|
|
314
325
|
def construct_row_by_schema(
|
|
@@ -43,7 +43,12 @@ def read_text(
|
|
|
43
43
|
) -> snowpark.DataFrame:
|
|
44
44
|
# TODO: handle stage name with double quotes
|
|
45
45
|
files_paths = get_file_paths_from_stage(path, session)
|
|
46
|
-
|
|
46
|
+
# Remove matching quotes from both ends of the path to get the stage name, if present.
|
|
47
|
+
if path and len(path) > 1 and path[0] == path[-1] and path[0] in ('"', "'"):
|
|
48
|
+
unquoted_path = path[1:-1]
|
|
49
|
+
else:
|
|
50
|
+
unquoted_path = path
|
|
51
|
+
stage_name = unquoted_path.split("/")[0]
|
|
47
52
|
line_sep = options.get("lineSep") or "\n"
|
|
48
53
|
column_name = (
|
|
49
54
|
schema[0].name if schema is not None and len(schema.fields) > 0 else '"value"'
|