snowflake-cli 2.8.2__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.
Files changed (240) hide show
  1. snowflake/cli/__about__.py +17 -0
  2. snowflake/cli/__init__.py +13 -0
  3. snowflake/cli/api/__init__.py +48 -0
  4. snowflake/cli/api/cli_global_context.py +390 -0
  5. snowflake/cli/api/commands/__init__.py +13 -0
  6. snowflake/cli/api/commands/alias.py +23 -0
  7. snowflake/cli/api/commands/decorators.py +354 -0
  8. snowflake/cli/api/commands/execution_metadata.py +40 -0
  9. snowflake/cli/api/commands/experimental_behaviour.py +19 -0
  10. snowflake/cli/api/commands/flags.py +662 -0
  11. snowflake/cli/api/commands/project_initialisation.py +65 -0
  12. snowflake/cli/api/commands/snow_typer.py +237 -0
  13. snowflake/cli/api/commands/typer_pre_execute.py +26 -0
  14. snowflake/cli/api/config.py +348 -0
  15. snowflake/cli/api/console/__init__.py +17 -0
  16. snowflake/cli/api/console/abc.py +89 -0
  17. snowflake/cli/api/console/console.py +134 -0
  18. snowflake/cli/api/console/enum.py +17 -0
  19. snowflake/cli/api/constants.py +79 -0
  20. snowflake/cli/api/errno.py +27 -0
  21. snowflake/cli/api/exceptions.py +164 -0
  22. snowflake/cli/api/feature_flags.py +55 -0
  23. snowflake/cli/api/identifiers.py +167 -0
  24. snowflake/cli/api/output/__init__.py +13 -0
  25. snowflake/cli/api/output/formats.py +20 -0
  26. snowflake/cli/api/output/types.py +118 -0
  27. snowflake/cli/api/plugins/__init__.py +13 -0
  28. snowflake/cli/api/plugins/command/__init__.py +72 -0
  29. snowflake/cli/api/plugins/command/plugin_hook_specs.py +21 -0
  30. snowflake/cli/api/plugins/plugin_config.py +32 -0
  31. snowflake/cli/api/project/__init__.py +13 -0
  32. snowflake/cli/api/project/definition.py +84 -0
  33. snowflake/cli/api/project/definition_manager.py +134 -0
  34. snowflake/cli/api/project/errors.py +56 -0
  35. snowflake/cli/api/project/project_verification.py +23 -0
  36. snowflake/cli/api/project/schemas/__init__.py +13 -0
  37. snowflake/cli/api/project/schemas/entities/application_entity.py +44 -0
  38. snowflake/cli/api/project/schemas/entities/application_package_entity.py +66 -0
  39. snowflake/cli/api/project/schemas/entities/common.py +78 -0
  40. snowflake/cli/api/project/schemas/entities/entities.py +30 -0
  41. snowflake/cli/api/project/schemas/identifier_model.py +49 -0
  42. snowflake/cli/api/project/schemas/native_app/__init__.py +13 -0
  43. snowflake/cli/api/project/schemas/native_app/application.py +62 -0
  44. snowflake/cli/api/project/schemas/native_app/native_app.py +93 -0
  45. snowflake/cli/api/project/schemas/native_app/package.py +78 -0
  46. snowflake/cli/api/project/schemas/native_app/path_mapping.py +65 -0
  47. snowflake/cli/api/project/schemas/project_definition.py +199 -0
  48. snowflake/cli/api/project/schemas/snowpark/__init__.py +13 -0
  49. snowflake/cli/api/project/schemas/snowpark/argument.py +28 -0
  50. snowflake/cli/api/project/schemas/snowpark/callable.py +69 -0
  51. snowflake/cli/api/project/schemas/snowpark/snowpark.py +36 -0
  52. snowflake/cli/api/project/schemas/streamlit/__init__.py +13 -0
  53. snowflake/cli/api/project/schemas/streamlit/streamlit.py +46 -0
  54. snowflake/cli/api/project/schemas/template.py +77 -0
  55. snowflake/cli/api/project/schemas/updatable_model.py +194 -0
  56. snowflake/cli/api/project/util.py +261 -0
  57. snowflake/cli/api/rendering/__init__.py +13 -0
  58. snowflake/cli/api/rendering/jinja.py +112 -0
  59. snowflake/cli/api/rendering/project_definition_templates.py +39 -0
  60. snowflake/cli/api/rendering/project_templates.py +98 -0
  61. snowflake/cli/api/rendering/sql_templates.py +60 -0
  62. snowflake/cli/api/rest_api.py +172 -0
  63. snowflake/cli/api/sanitizers.py +43 -0
  64. snowflake/cli/api/secure_path.py +362 -0
  65. snowflake/cli/api/secure_utils.py +29 -0
  66. snowflake/cli/api/sql_execution.py +260 -0
  67. snowflake/cli/api/utils/__init__.py +13 -0
  68. snowflake/cli/api/utils/cursor.py +34 -0
  69. snowflake/cli/api/utils/definition_rendering.py +383 -0
  70. snowflake/cli/api/utils/dict_utils.py +73 -0
  71. snowflake/cli/api/utils/error_handling.py +23 -0
  72. snowflake/cli/api/utils/graph.py +97 -0
  73. snowflake/cli/api/utils/models.py +63 -0
  74. snowflake/cli/api/utils/naming_utils.py +13 -0
  75. snowflake/cli/api/utils/path_utils.py +36 -0
  76. snowflake/cli/api/utils/templating_functions.py +144 -0
  77. snowflake/cli/api/utils/types.py +35 -0
  78. snowflake/cli/app/__init__.py +22 -0
  79. snowflake/cli/app/__main__.py +31 -0
  80. snowflake/cli/app/api_impl/__init__.py +13 -0
  81. snowflake/cli/app/api_impl/plugin/__init__.py +13 -0
  82. snowflake/cli/app/api_impl/plugin/plugin_config_provider_impl.py +66 -0
  83. snowflake/cli/app/build_and_push.sh +8 -0
  84. snowflake/cli/app/cli_app.py +243 -0
  85. snowflake/cli/app/commands_registration/__init__.py +33 -0
  86. snowflake/cli/app/commands_registration/builtin_plugins.py +54 -0
  87. snowflake/cli/app/commands_registration/command_plugins_loader.py +169 -0
  88. snowflake/cli/app/commands_registration/commands_registration_with_callbacks.py +105 -0
  89. snowflake/cli/app/commands_registration/exception_logging.py +26 -0
  90. snowflake/cli/app/commands_registration/threadsafe.py +48 -0
  91. snowflake/cli/app/commands_registration/typer_registration.py +153 -0
  92. snowflake/cli/app/constants.py +19 -0
  93. snowflake/cli/app/dev/__init__.py +13 -0
  94. snowflake/cli/app/dev/commands_structure.py +48 -0
  95. snowflake/cli/app/dev/docs/__init__.py +13 -0
  96. snowflake/cli/app/dev/docs/commands_docs_generator.py +100 -0
  97. snowflake/cli/app/dev/docs/generator.py +35 -0
  98. snowflake/cli/app/dev/docs/project_definition_docs_generator.py +58 -0
  99. snowflake/cli/app/dev/docs/project_definition_generate_json_schema.py +227 -0
  100. snowflake/cli/app/dev/docs/template_utils.py +23 -0
  101. snowflake/cli/app/dev/docs/templates/definition_description.rst.jinja2 +38 -0
  102. snowflake/cli/app/dev/docs/templates/overview.rst.jinja2 +9 -0
  103. snowflake/cli/app/dev/docs/templates/usage.rst.jinja2 +57 -0
  104. snowflake/cli/app/dev/pycharm_remote_debug.py +46 -0
  105. snowflake/cli/app/loggers.py +199 -0
  106. snowflake/cli/app/main_typer.py +62 -0
  107. snowflake/cli/app/printing.py +181 -0
  108. snowflake/cli/app/snow_connector.py +243 -0
  109. snowflake/cli/app/telemetry.py +189 -0
  110. snowflake/cli/plugins/__init__.py +13 -0
  111. snowflake/cli/plugins/connection/__init__.py +13 -0
  112. snowflake/cli/plugins/connection/commands.py +330 -0
  113. snowflake/cli/plugins/connection/plugin_spec.py +30 -0
  114. snowflake/cli/plugins/connection/util.py +179 -0
  115. snowflake/cli/plugins/cortex/__init__.py +13 -0
  116. snowflake/cli/plugins/cortex/commands.py +327 -0
  117. snowflake/cli/plugins/cortex/constants.py +17 -0
  118. snowflake/cli/plugins/cortex/manager.py +189 -0
  119. snowflake/cli/plugins/cortex/plugin_spec.py +30 -0
  120. snowflake/cli/plugins/cortex/types.py +22 -0
  121. snowflake/cli/plugins/git/__init__.py +13 -0
  122. snowflake/cli/plugins/git/commands.py +354 -0
  123. snowflake/cli/plugins/git/manager.py +105 -0
  124. snowflake/cli/plugins/git/plugin_spec.py +30 -0
  125. snowflake/cli/plugins/init/__init__.py +13 -0
  126. snowflake/cli/plugins/init/commands.py +248 -0
  127. snowflake/cli/plugins/init/plugin_spec.py +30 -0
  128. snowflake/cli/plugins/nativeapp/__init__.py +13 -0
  129. snowflake/cli/plugins/nativeapp/artifacts.py +742 -0
  130. snowflake/cli/plugins/nativeapp/codegen/__init__.py +13 -0
  131. snowflake/cli/plugins/nativeapp/codegen/artifact_processor.py +91 -0
  132. snowflake/cli/plugins/nativeapp/codegen/compiler.py +130 -0
  133. snowflake/cli/plugins/nativeapp/codegen/sandbox.py +306 -0
  134. snowflake/cli/plugins/nativeapp/codegen/setup/native_app_setup_processor.py +172 -0
  135. snowflake/cli/plugins/nativeapp/codegen/setup/setup_driver.py.source +56 -0
  136. snowflake/cli/plugins/nativeapp/codegen/snowpark/callback_source.py.jinja +181 -0
  137. snowflake/cli/plugins/nativeapp/codegen/snowpark/extension_function_utils.py +217 -0
  138. snowflake/cli/plugins/nativeapp/codegen/snowpark/models.py +61 -0
  139. snowflake/cli/plugins/nativeapp/codegen/snowpark/python_processor.py +528 -0
  140. snowflake/cli/plugins/nativeapp/commands.py +439 -0
  141. snowflake/cli/plugins/nativeapp/common_flags.py +44 -0
  142. snowflake/cli/plugins/nativeapp/constants.py +27 -0
  143. snowflake/cli/plugins/nativeapp/exceptions.py +122 -0
  144. snowflake/cli/plugins/nativeapp/feature_flags.py +24 -0
  145. snowflake/cli/plugins/nativeapp/init.py +345 -0
  146. snowflake/cli/plugins/nativeapp/manager.py +823 -0
  147. snowflake/cli/plugins/nativeapp/plugin_spec.py +30 -0
  148. snowflake/cli/plugins/nativeapp/policy.py +50 -0
  149. snowflake/cli/plugins/nativeapp/project_model.py +195 -0
  150. snowflake/cli/plugins/nativeapp/run_processor.py +389 -0
  151. snowflake/cli/plugins/nativeapp/teardown_processor.py +301 -0
  152. snowflake/cli/plugins/nativeapp/utils.py +98 -0
  153. snowflake/cli/plugins/nativeapp/v2_conversions/v2_to_v1_decorator.py +135 -0
  154. snowflake/cli/plugins/nativeapp/version/__init__.py +13 -0
  155. snowflake/cli/plugins/nativeapp/version/commands.py +170 -0
  156. snowflake/cli/plugins/nativeapp/version/version_processor.py +362 -0
  157. snowflake/cli/plugins/notebook/__init__.py +13 -0
  158. snowflake/cli/plugins/notebook/commands.py +85 -0
  159. snowflake/cli/plugins/notebook/exceptions.py +20 -0
  160. snowflake/cli/plugins/notebook/manager.py +71 -0
  161. snowflake/cli/plugins/notebook/plugin_spec.py +30 -0
  162. snowflake/cli/plugins/notebook/types.py +15 -0
  163. snowflake/cli/plugins/object/__init__.py +13 -0
  164. snowflake/cli/plugins/object/command_aliases.py +95 -0
  165. snowflake/cli/plugins/object/commands.py +181 -0
  166. snowflake/cli/plugins/object/common.py +85 -0
  167. snowflake/cli/plugins/object/manager.py +97 -0
  168. snowflake/cli/plugins/object/plugin_spec.py +30 -0
  169. snowflake/cli/plugins/object_stage_deprecated/__init__.py +15 -0
  170. snowflake/cli/plugins/object_stage_deprecated/commands.py +122 -0
  171. snowflake/cli/plugins/object_stage_deprecated/plugin_spec.py +32 -0
  172. snowflake/cli/plugins/snowpark/__init__.py +13 -0
  173. snowflake/cli/plugins/snowpark/commands.py +546 -0
  174. snowflake/cli/plugins/snowpark/common.py +307 -0
  175. snowflake/cli/plugins/snowpark/manager.py +109 -0
  176. snowflake/cli/plugins/snowpark/models.py +157 -0
  177. snowflake/cli/plugins/snowpark/package/__init__.py +13 -0
  178. snowflake/cli/plugins/snowpark/package/anaconda_packages.py +233 -0
  179. snowflake/cli/plugins/snowpark/package/commands.py +256 -0
  180. snowflake/cli/plugins/snowpark/package/manager.py +44 -0
  181. snowflake/cli/plugins/snowpark/package/utils.py +26 -0
  182. snowflake/cli/plugins/snowpark/package_utils.py +354 -0
  183. snowflake/cli/plugins/snowpark/plugin_spec.py +30 -0
  184. snowflake/cli/plugins/snowpark/snowpark_package_paths.py +65 -0
  185. snowflake/cli/plugins/snowpark/snowpark_shared.py +95 -0
  186. snowflake/cli/plugins/snowpark/zipper.py +81 -0
  187. snowflake/cli/plugins/spcs/__init__.py +35 -0
  188. snowflake/cli/plugins/spcs/common.py +99 -0
  189. snowflake/cli/plugins/spcs/compute_pool/__init__.py +13 -0
  190. snowflake/cli/plugins/spcs/compute_pool/commands.py +241 -0
  191. snowflake/cli/plugins/spcs/compute_pool/manager.py +121 -0
  192. snowflake/cli/plugins/spcs/image_registry/__init__.py +13 -0
  193. snowflake/cli/plugins/spcs/image_registry/commands.py +65 -0
  194. snowflake/cli/plugins/spcs/image_registry/manager.py +105 -0
  195. snowflake/cli/plugins/spcs/image_repository/__init__.py +13 -0
  196. snowflake/cli/plugins/spcs/image_repository/commands.py +202 -0
  197. snowflake/cli/plugins/spcs/image_repository/manager.py +84 -0
  198. snowflake/cli/plugins/spcs/jobs/__init__.py +13 -0
  199. snowflake/cli/plugins/spcs/jobs/commands.py +78 -0
  200. snowflake/cli/plugins/spcs/jobs/manager.py +53 -0
  201. snowflake/cli/plugins/spcs/plugin_spec.py +30 -0
  202. snowflake/cli/plugins/spcs/services/__init__.py +13 -0
  203. snowflake/cli/plugins/spcs/services/commands.py +312 -0
  204. snowflake/cli/plugins/spcs/services/manager.py +170 -0
  205. snowflake/cli/plugins/sql/__init__.py +13 -0
  206. snowflake/cli/plugins/sql/commands.py +83 -0
  207. snowflake/cli/plugins/sql/manager.py +92 -0
  208. snowflake/cli/plugins/sql/plugin_spec.py +30 -0
  209. snowflake/cli/plugins/sql/snowsql_templating.py +28 -0
  210. snowflake/cli/plugins/stage/__init__.py +13 -0
  211. snowflake/cli/plugins/stage/commands.py +263 -0
  212. snowflake/cli/plugins/stage/diff.py +326 -0
  213. snowflake/cli/plugins/stage/manager.py +577 -0
  214. snowflake/cli/plugins/stage/md5.py +160 -0
  215. snowflake/cli/plugins/stage/plugin_spec.py +30 -0
  216. snowflake/cli/plugins/streamlit/__init__.py +13 -0
  217. snowflake/cli/plugins/streamlit/commands.py +179 -0
  218. snowflake/cli/plugins/streamlit/manager.py +222 -0
  219. snowflake/cli/plugins/streamlit/plugin_spec.py +30 -0
  220. snowflake/cli/plugins/workspace/__init__.py +13 -0
  221. snowflake/cli/plugins/workspace/commands.py +35 -0
  222. snowflake/cli/plugins/workspace/plugin_spec.py +30 -0
  223. snowflake/cli/templates/default_snowpark/.gitignore +4 -0
  224. snowflake/cli/templates/default_snowpark/app/__init__.py +0 -0
  225. snowflake/cli/templates/default_snowpark/app/common.py +2 -0
  226. snowflake/cli/templates/default_snowpark/app/functions.py +15 -0
  227. snowflake/cli/templates/default_snowpark/app/procedures.py +22 -0
  228. snowflake/cli/templates/default_snowpark/requirements.txt +1 -0
  229. snowflake/cli/templates/default_snowpark/snowflake.yml +23 -0
  230. snowflake/cli/templates/default_streamlit/.gitignore +4 -0
  231. snowflake/cli/templates/default_streamlit/common/hello.py +2 -0
  232. snowflake/cli/templates/default_streamlit/environment.yml +6 -0
  233. snowflake/cli/templates/default_streamlit/pages/my_page.py +3 -0
  234. snowflake/cli/templates/default_streamlit/snowflake.yml +10 -0
  235. snowflake/cli/templates/default_streamlit/streamlit_app.py +4 -0
  236. snowflake_cli-2.8.2.dist-info/METADATA +325 -0
  237. snowflake_cli-2.8.2.dist-info/RECORD +240 -0
  238. snowflake_cli-2.8.2.dist-info/WHEEL +4 -0
  239. snowflake_cli-2.8.2.dist-info/entry_points.txt +2 -0
  240. snowflake_cli-2.8.2.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,577 @@
1
+ # Copyright (c) 2024 Snowflake Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import fnmatch
18
+ import glob
19
+ import logging
20
+ import re
21
+ import sys
22
+ from contextlib import nullcontext
23
+ from dataclasses import dataclass
24
+ from os import path
25
+ from pathlib import Path
26
+ from textwrap import dedent
27
+ from typing import Dict, List, Optional, Union
28
+
29
+ from click import ClickException
30
+ from snowflake.cli.api.commands.flags import (
31
+ OnErrorType,
32
+ Variable,
33
+ parse_key_value_variables,
34
+ )
35
+ from snowflake.cli.api.console import cli_console
36
+ from snowflake.cli.api.constants import PYTHON_3_12
37
+ from snowflake.cli.api.identifiers import FQN
38
+ from snowflake.cli.api.project.util import to_string_literal
39
+ from snowflake.cli.api.secure_path import SecurePath
40
+ from snowflake.cli.api.sql_execution import SqlExecutionMixin
41
+ from snowflake.cli.api.utils.path_utils import path_resolver
42
+ from snowflake.cli.plugins.snowpark.package_utils import parse_requirements
43
+ from snowflake.connector import DictCursor, ProgrammingError
44
+ from snowflake.connector.cursor import SnowflakeCursor
45
+
46
+ if sys.version_info < PYTHON_3_12:
47
+ # Because Snowpark works only below 3.12 and to use @sproc Session must be imported here.
48
+ from snowflake.snowpark import Session
49
+
50
+ log = logging.getLogger(__name__)
51
+
52
+
53
+ UNQUOTED_FILE_URI_REGEX = r"[\w/*?\-.=&{}$#[\]\"\\!@%^+:]+"
54
+ USER_STAGE_PREFIX = "@~"
55
+ EXECUTE_SUPPORTED_FILES_FORMATS = (
56
+ ".sql",
57
+ ".py",
58
+ ) # tuple to preserve order but it's a set
59
+
60
+
61
+ @dataclass
62
+ class StagePathParts:
63
+ directory: str
64
+ stage: str
65
+ stage_name: str
66
+ is_directory: bool
67
+
68
+ @classmethod
69
+ def get_directory(cls, stage_path: str) -> str:
70
+ return "/".join(Path(stage_path).parts[1:])
71
+
72
+ @property
73
+ def path(self) -> str:
74
+ raise NotImplementedError
75
+
76
+ @property
77
+ def full_path(self) -> str:
78
+ raise NotImplementedError
79
+
80
+ def replace_stage_prefix(self, file_path: str) -> str:
81
+ raise NotImplementedError
82
+
83
+ def add_stage_prefix(self, file_path: str) -> str:
84
+ raise NotImplementedError
85
+
86
+ def get_directory_from_file_path(self, file_path: str) -> List[str]:
87
+ raise NotImplementedError
88
+
89
+ def get_full_stage_path(self, path: str):
90
+ if prefix := FQN.from_stage(self.stage).prefix:
91
+ return prefix + "." + path
92
+ return path
93
+
94
+ def get_standard_stage_path(self) -> str:
95
+ path = self.path
96
+ return f"@{path}{'/'if self.is_directory and not path.endswith('/') else ''}"
97
+
98
+ def get_standard_stage_directory_path(self) -> str:
99
+ path = self.get_standard_stage_path()
100
+ if not path.endswith("/"):
101
+ return path + "/"
102
+ return path
103
+
104
+
105
+ @dataclass
106
+ class DefaultStagePathParts(StagePathParts):
107
+ """
108
+ For path like @db.schema.stage/dir the values will be:
109
+ directory = dir
110
+ stage = @db.schema.stage
111
+ stage_name = stage
112
+ For `@stage/dir` to
113
+ stage -> @stage
114
+ stage_name -> stage
115
+ directory -> dir
116
+ """
117
+
118
+ def __init__(self, stage_path: str):
119
+ self.directory = self.get_directory(stage_path)
120
+ self.stage = StageManager.get_stage_from_path(stage_path)
121
+ stage_name = self.stage.split(".")[-1]
122
+ stage_name = stage_name[1:] if stage_name.startswith("@") else stage_name
123
+ self.stage_name = stage_name
124
+ self.is_directory = True if stage_path.endswith("/") else False
125
+
126
+ @property
127
+ def path(self) -> str:
128
+ return f"{self.stage_name.rstrip('/')}/{self.directory}"
129
+
130
+ @property
131
+ def full_path(self) -> str:
132
+ return f"{self.stage.rstrip('/')}/{self.directory}"
133
+
134
+ def replace_stage_prefix(self, file_path: str) -> str:
135
+ stage = Path(self.stage).parts[0]
136
+ file_path_without_prefix = Path(file_path).parts[1:]
137
+ return f"{stage}/{'/'.join(file_path_without_prefix)}"
138
+
139
+ def add_stage_prefix(self, file_path: str) -> str:
140
+ stage = self.stage.rstrip("/")
141
+ return f"{stage}/{file_path.lstrip('/')}"
142
+
143
+ def get_directory_from_file_path(self, file_path: str) -> List[str]:
144
+ stage_path_length = len(Path(self.directory).parts)
145
+ return list(Path(file_path).parts[1 + stage_path_length : -1])
146
+
147
+
148
+ @dataclass
149
+ class UserStagePathParts(StagePathParts):
150
+ """
151
+ For path like @db.schema.stage/dir the values will be:
152
+ directory = dir
153
+ stage = @~
154
+ stage_name = @~
155
+ """
156
+
157
+ def __init__(self, stage_path: str):
158
+ self.directory = self.get_directory(stage_path)
159
+ self.stage = USER_STAGE_PREFIX
160
+ self.stage_name = USER_STAGE_PREFIX
161
+ self.is_directory = True if stage_path.endswith("/") else False
162
+
163
+ @classmethod
164
+ def get_directory(cls, stage_path: str) -> str:
165
+ if Path(stage_path).parts[0] == USER_STAGE_PREFIX:
166
+ return super().get_directory(stage_path)
167
+ return stage_path
168
+
169
+ @property
170
+ def path(self) -> str:
171
+ return f"{self.directory}"
172
+
173
+ @property
174
+ def full_path(self) -> str:
175
+ return f"{self.stage}/{self.directory}"
176
+
177
+ def replace_stage_prefix(self, file_path: str) -> str:
178
+ if Path(file_path).parts[0] == self.stage_name:
179
+ return file_path
180
+ return f"{self.stage}/{file_path}"
181
+
182
+ def add_stage_prefix(self, file_path: str) -> str:
183
+ return f"{self.stage}/{file_path}"
184
+
185
+ def get_directory_from_file_path(self, file_path: str) -> List[str]:
186
+ stage_path_length = len(Path(self.directory).parts)
187
+ return list(Path(file_path).parts[stage_path_length:-1])
188
+
189
+
190
+ class StageManager(SqlExecutionMixin):
191
+ def __init__(self):
192
+ super().__init__()
193
+ self._python_exe_procedure = None
194
+
195
+ @staticmethod
196
+ def get_standard_stage_prefix(name: str | FQN) -> str:
197
+ if isinstance(name, FQN):
198
+ name = name.identifier
199
+ # Handle embedded stages
200
+ if name.startswith("snow://") or name.startswith("@"):
201
+ return name
202
+
203
+ return f"@{name}"
204
+
205
+ @staticmethod
206
+ def get_stage_from_path(path: str):
207
+ """
208
+ Returns stage name from potential path on stage. For example
209
+ db.schema.stage/foo/bar -> db.schema.stage
210
+ """
211
+ return Path(path).parts[0]
212
+
213
+ @staticmethod
214
+ def quote_stage_name(name: str) -> str:
215
+ if name.startswith("'") and name.endswith("'"):
216
+ return name # already quoted
217
+
218
+ standard_name = StageManager.get_standard_stage_prefix(name)
219
+ if standard_name.startswith("@") and not re.fullmatch(
220
+ r"@([\w./$])+", standard_name
221
+ ):
222
+ return to_string_literal(standard_name)
223
+
224
+ return standard_name
225
+
226
+ def _to_uri(self, local_path: str):
227
+ uri = f"file://{local_path}"
228
+ if re.fullmatch(UNQUOTED_FILE_URI_REGEX, uri):
229
+ return uri
230
+ return to_string_literal(uri)
231
+
232
+ def list_files(self, stage_name: str, pattern: str | None = None) -> DictCursor:
233
+ stage_name = self.get_standard_stage_prefix(stage_name)
234
+ query = f"ls {self.quote_stage_name(stage_name)}"
235
+ if pattern is not None:
236
+ query += f" pattern = '{pattern}'"
237
+ return self._execute_query(query, cursor_class=DictCursor)
238
+
239
+ @staticmethod
240
+ def _assure_is_existing_directory(path: Path) -> None:
241
+ spath = SecurePath(path)
242
+ if not spath.exists():
243
+ spath.mkdir(parents=True)
244
+ spath.assert_is_directory()
245
+
246
+ def get(
247
+ self, stage_path: str, dest_path: Path, parallel: int = 4
248
+ ) -> SnowflakeCursor:
249
+ stage_path = self.get_standard_stage_prefix(stage_path)
250
+ self._assure_is_existing_directory(dest_path)
251
+ dest_directory = f"{dest_path}/"
252
+ return self._execute_query(
253
+ f"get {self.quote_stage_name(stage_path)} {self._to_uri(dest_directory)} parallel={parallel}"
254
+ )
255
+
256
+ def get_recursive(
257
+ self, stage_path: str, dest_path: Path, parallel: int = 4
258
+ ) -> List[SnowflakeCursor]:
259
+ stage_path_parts = self._stage_path_part_factory(stage_path)
260
+
261
+ results = []
262
+ for file_path in self.iter_stage(stage_path):
263
+ dest_directory = dest_path
264
+ for path_part in stage_path_parts.get_directory_from_file_path(file_path):
265
+ dest_directory = dest_directory / path_part
266
+ self._assure_is_existing_directory(dest_directory)
267
+
268
+ result = self._execute_query(
269
+ f"get {self.quote_stage_name(stage_path_parts.replace_stage_prefix(file_path))} {self._to_uri(f'{dest_directory}/')} parallel={parallel}"
270
+ )
271
+ results.append(result)
272
+
273
+ return results
274
+
275
+ def put(
276
+ self,
277
+ local_path: Union[str, Path],
278
+ stage_path: str,
279
+ parallel: int = 4,
280
+ overwrite: bool = False,
281
+ role: Optional[str] = None,
282
+ auto_compress: bool = False,
283
+ ) -> SnowflakeCursor:
284
+ """
285
+ This method will take a file path from the user's system and put it into a Snowflake stage,
286
+ which includes its fully qualified name as well as the path within the stage.
287
+ If provided with a role, then temporarily use this role to perform the operation above,
288
+ and switch back to the original role for the next commands to run.
289
+ """
290
+ with self.use_role(role) if role else nullcontext():
291
+ stage_path = self.get_standard_stage_prefix(stage_path)
292
+ local_resolved_path = path_resolver(str(local_path))
293
+ log.info("Uploading %s to %s", local_resolved_path, stage_path)
294
+ cursor = self._execute_query(
295
+ f"put {self._to_uri(local_resolved_path)} {self.quote_stage_name(stage_path)} "
296
+ f"auto_compress={str(auto_compress).lower()} parallel={parallel} overwrite={overwrite}"
297
+ )
298
+ return cursor
299
+
300
+ def copy_files(self, source_path: str, destination_path: str) -> SnowflakeCursor:
301
+ source_path_parts = self._stage_path_part_factory(source_path)
302
+ destination_path_parts = self._stage_path_part_factory(destination_path)
303
+
304
+ if isinstance(destination_path_parts, UserStagePathParts):
305
+ raise ClickException(
306
+ "Destination path cannot be a user stage. Please provide a named stage."
307
+ )
308
+
309
+ source = source_path_parts.get_standard_stage_path()
310
+ destination = destination_path_parts.get_standard_stage_directory_path()
311
+ log.info("Copying files from %s to %s", source, destination)
312
+ query = f"copy files into {destination} from {source}"
313
+ return self._execute_query(query)
314
+
315
+ def remove(
316
+ self, stage_name: str, path: str, role: Optional[str] = None
317
+ ) -> SnowflakeCursor:
318
+ """
319
+ This method will take a file path that exists on a Snowflake stage,
320
+ and remove it from the stage.
321
+ If provided with a role, then temporarily use this role to perform the operation above,
322
+ and switch back to the original role for the next commands to run.
323
+ """
324
+ with self.use_role(role) if role else nullcontext():
325
+ stage_name = self.get_standard_stage_prefix(stage_name)
326
+ path = path if path.startswith("/") else "/" + path
327
+ quoted_stage_name = self.quote_stage_name(f"{stage_name}{path}")
328
+ return self._execute_query(f"remove {quoted_stage_name}")
329
+
330
+ def create(self, fqn: FQN, comment: Optional[str] = None) -> SnowflakeCursor:
331
+ query = f"create stage if not exists {fqn.sql_identifier}"
332
+ if comment:
333
+ query += f" comment='{comment}'"
334
+ return self._execute_query(query)
335
+
336
+ def iter_stage(self, stage_path: str):
337
+ for file in self.list_files(stage_path).fetchall():
338
+ yield file["name"]
339
+
340
+ def execute(
341
+ self,
342
+ stage_path: str,
343
+ on_error: OnErrorType,
344
+ variables: Optional[List[str]] = None,
345
+ ):
346
+ stage_path_parts = self._stage_path_part_factory(stage_path)
347
+ all_files_list = self._get_files_list_from_stage(stage_path_parts)
348
+
349
+ all_files_with_stage_name_prefix = [
350
+ stage_path_parts.get_directory(file) for file in all_files_list
351
+ ]
352
+
353
+ # filter files from stage if match stage_path pattern
354
+ filtered_file_list = self._filter_files_list(
355
+ stage_path_parts, all_files_with_stage_name_prefix
356
+ )
357
+
358
+ if not filtered_file_list:
359
+ raise ClickException(f"No files matched pattern '{stage_path}'")
360
+
361
+ # sort filtered files in alphabetical order with directories at the end
362
+ sorted_file_path_list = sorted(
363
+ filtered_file_list, key=lambda f: (path.dirname(f), path.basename(f))
364
+ )
365
+
366
+ parsed_variables = parse_key_value_variables(variables)
367
+ sql_variables = self._parse_execute_variables(parsed_variables)
368
+ python_variables = {str(v.key): v.value for v in parsed_variables}
369
+ results = []
370
+
371
+ if any(file.endswith(".py") for file in sorted_file_path_list):
372
+ self._python_exe_procedure = self._bootstrap_snowpark_execution_environment(
373
+ stage_path_parts
374
+ )
375
+
376
+ for file_path in sorted_file_path_list:
377
+ file_stage_path = stage_path_parts.add_stage_prefix(file_path)
378
+ if file_path.endswith(".py"):
379
+ result = self._execute_python(
380
+ file_stage_path=file_stage_path,
381
+ on_error=on_error,
382
+ variables=python_variables,
383
+ )
384
+ else:
385
+ result = self._call_execute_immediate(
386
+ file_stage_path=file_stage_path,
387
+ variables=sql_variables,
388
+ on_error=on_error,
389
+ )
390
+ results.append(result)
391
+
392
+ return results
393
+
394
+ def _get_files_list_from_stage(
395
+ self, stage_path_parts: StagePathParts, pattern: str | None = None
396
+ ) -> List[str]:
397
+ files_list_result = self.list_files(
398
+ stage_path_parts.stage, pattern=pattern
399
+ ).fetchall()
400
+
401
+ if not files_list_result:
402
+ raise ClickException(f"No files found on stage '{stage_path_parts.stage}'")
403
+
404
+ return [f["name"] for f in files_list_result]
405
+
406
+ def _filter_files_list(
407
+ self, stage_path_parts: StagePathParts, files_on_stage: List[str]
408
+ ) -> List[str]:
409
+ if not stage_path_parts.directory:
410
+ return self._filter_supported_files(files_on_stage)
411
+
412
+ stage_path = stage_path_parts.directory
413
+
414
+ # Exact file path was provided if stage_path in file list
415
+ if stage_path in files_on_stage:
416
+ filtered_files = self._filter_supported_files([stage_path])
417
+ if filtered_files:
418
+ return filtered_files
419
+ else:
420
+ raise ClickException(
421
+ f"Invalid file extension, only {', '.join(EXECUTE_SUPPORTED_FILES_FORMATS)} files are allowed."
422
+ )
423
+ # Filter with fnmatch if contains `*` or `?`
424
+ if glob.has_magic(stage_path):
425
+ filtered_files = fnmatch.filter(files_on_stage, stage_path)
426
+ else:
427
+ # Path to directory was provided
428
+ filtered_files = fnmatch.filter(files_on_stage, f"{stage_path}*")
429
+ return self._filter_supported_files(filtered_files)
430
+
431
+ @staticmethod
432
+ def _filter_supported_files(files: List[str]) -> List[str]:
433
+ return [f for f in files if Path(f).suffix in EXECUTE_SUPPORTED_FILES_FORMATS]
434
+
435
+ @staticmethod
436
+ def _parse_execute_variables(variables: List[Variable]) -> Optional[str]:
437
+ if not variables:
438
+ return None
439
+ query_parameters = [f"{v.key}=>{v.value}" for v in variables]
440
+ return f" using ({', '.join(query_parameters)})"
441
+
442
+ @staticmethod
443
+ def _success_result(file: str):
444
+ cli_console.warning(f"SUCCESS - {file}")
445
+ return {"File": file, "Status": "SUCCESS", "Error": None}
446
+
447
+ @staticmethod
448
+ def _error_result(file: str, msg: str):
449
+ cli_console.warning(f"FAILURE - {file}")
450
+ return {"File": file, "Status": "FAILURE", "Error": msg}
451
+
452
+ @staticmethod
453
+ def _handle_execution_exception(on_error: OnErrorType, exception: Exception):
454
+ if on_error == OnErrorType.BREAK:
455
+ raise exception
456
+
457
+ def _call_execute_immediate(
458
+ self,
459
+ file_stage_path: str,
460
+ variables: Optional[str],
461
+ on_error: OnErrorType,
462
+ ) -> Dict:
463
+ try:
464
+ query = f"execute immediate from {file_stage_path}"
465
+ if variables:
466
+ query += variables
467
+ self._execute_query(query)
468
+ return StageManager._success_result(file=file_stage_path)
469
+ except ProgrammingError as e:
470
+ StageManager._handle_execution_exception(on_error=on_error, exception=e)
471
+ return StageManager._error_result(file=file_stage_path, msg=e.msg)
472
+
473
+ @staticmethod
474
+ def _stage_path_part_factory(stage_path: str) -> StagePathParts:
475
+ stage_path = StageManager.get_standard_stage_prefix(stage_path)
476
+ if stage_path.startswith(USER_STAGE_PREFIX):
477
+ return UserStagePathParts(stage_path)
478
+ return DefaultStagePathParts(stage_path)
479
+
480
+ def _check_for_requirements_file(
481
+ self, stage_path_parts: StagePathParts
482
+ ) -> List[str]:
483
+ """Looks for requirements.txt file on stage."""
484
+ req_files_on_stage = self._get_files_list_from_stage(
485
+ stage_path_parts, pattern=r".*requirements\.txt$"
486
+ )
487
+ if not req_files_on_stage:
488
+ return []
489
+
490
+ # Construct all possible path for requirements file for this context
491
+ # We don't use os.path or pathlib to preserve compatibility on Windows
492
+ req_file_name = "requirements.txt"
493
+ path_parts = stage_path_parts.path.split("/")
494
+ possible_req_files = []
495
+
496
+ while path_parts:
497
+ current_file = "/".join([*path_parts, req_file_name])
498
+ possible_req_files.append(str(current_file))
499
+ path_parts = path_parts[:-1]
500
+
501
+ # Now for every possible path check if the file exists on stage,
502
+ # if yes break, we use the first possible file
503
+ requirements_file = None
504
+ for req_file in possible_req_files:
505
+ if req_file in req_files_on_stage:
506
+ requirements_file = req_file
507
+ break
508
+
509
+ # If we haven't found any matching requirements
510
+ if requirements_file is None:
511
+ return []
512
+
513
+ # req_file at this moment is the first found requirements file
514
+ with SecurePath.temporary_directory() as tmp_dir:
515
+ self.get(
516
+ stage_path_parts.get_full_stage_path(requirements_file), tmp_dir.path
517
+ )
518
+ requirements = parse_requirements(
519
+ requirements_file=tmp_dir / "requirements.txt"
520
+ )
521
+
522
+ return [req.package_name for req in requirements]
523
+
524
+ def _bootstrap_snowpark_execution_environment(
525
+ self, stage_path_parts: StagePathParts
526
+ ):
527
+ """Prepares Snowpark session for executing Python code remotely."""
528
+ if sys.version_info >= PYTHON_3_12:
529
+ raise ClickException(
530
+ f"Executing python files is not supported in Python >= 3.12. Current version: {sys.version}"
531
+ )
532
+
533
+ from snowflake.snowpark.functions import sproc
534
+
535
+ self.snowpark_session.add_packages("snowflake-snowpark-python")
536
+ self.snowpark_session.add_packages("snowflake.core")
537
+ requirements = self._check_for_requirements_file(stage_path_parts)
538
+ self.snowpark_session.add_packages(*requirements)
539
+
540
+ @sproc(is_permanent=False)
541
+ def _python_execution_procedure(
542
+ _: Session, file_path: str, variables: Dict | None = None
543
+ ) -> None:
544
+ """Snowpark session-scoped stored procedure to execute content of provided python file."""
545
+ import json
546
+
547
+ from snowflake.snowpark.files import SnowflakeFile
548
+
549
+ with SnowflakeFile.open(file_path, require_scoped_url=False) as f:
550
+ file_content: str = f.read() # type: ignore
551
+
552
+ wrapper = dedent(
553
+ f"""\
554
+ import os
555
+ os.environ.update({json.dumps(variables)})
556
+ """
557
+ )
558
+
559
+ exec(wrapper + file_content)
560
+
561
+ return _python_execution_procedure
562
+
563
+ def _execute_python(
564
+ self, file_stage_path: str, on_error: OnErrorType, variables: Dict
565
+ ):
566
+ """
567
+ Executes Python file from stage using a Snowpark temporary procedure.
568
+ Currently, there's no option to pass input to the execution.
569
+ """
570
+ from snowflake.snowpark.exceptions import SnowparkSQLException
571
+
572
+ try:
573
+ self._python_exe_procedure(self.get_standard_stage_prefix(file_stage_path), variables) # type: ignore
574
+ return StageManager._success_result(file=file_stage_path)
575
+ except SnowparkSQLException as e:
576
+ StageManager._handle_execution_exception(on_error=on_error, exception=e)
577
+ return StageManager._error_result(file=file_stage_path, msg=e.message)