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,528 @@
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 json
18
+ import re
19
+ from pathlib import Path
20
+ from textwrap import dedent
21
+ from typing import Any, Dict, List, Optional, Set
22
+
23
+ from pydantic import ValidationError
24
+ from snowflake.cli.api.console import cli_console as cc
25
+ from snowflake.cli.api.project.schemas.native_app.path_mapping import (
26
+ PathMapping,
27
+ ProcessorMapping,
28
+ )
29
+ from snowflake.cli.api.rendering.jinja import jinja_render_from_file
30
+ from snowflake.cli.plugins.nativeapp.artifacts import (
31
+ BundleMap,
32
+ find_setup_script_file,
33
+ )
34
+ from snowflake.cli.plugins.nativeapp.codegen.artifact_processor import (
35
+ ArtifactProcessor,
36
+ is_python_file_artifact,
37
+ )
38
+ from snowflake.cli.plugins.nativeapp.codegen.sandbox import (
39
+ ExecutionEnvironmentType,
40
+ SandboxExecutionError,
41
+ execute_script_in_sandbox,
42
+ )
43
+ from snowflake.cli.plugins.nativeapp.codegen.snowpark.extension_function_utils import (
44
+ deannotate_module_source,
45
+ ensure_all_string_literals,
46
+ ensure_string_literal,
47
+ get_function_type_signature_for_grant,
48
+ get_qualified_object_name,
49
+ get_sql_argument_signature,
50
+ get_sql_object_type,
51
+ )
52
+ from snowflake.cli.plugins.nativeapp.codegen.snowpark.models import (
53
+ ExtensionFunctionTypeEnum,
54
+ NativeAppExtensionFunction,
55
+ )
56
+ from snowflake.cli.plugins.nativeapp.project_model import NativeAppProjectModel
57
+ from snowflake.cli.plugins.stage.diff import to_stage_path
58
+
59
+ DEFAULT_TIMEOUT = 30
60
+ TEMPLATE_PATH = Path(__file__).parent / "callback_source.py.jinja"
61
+ SNOWPARK_LIB_NAME = "snowflake-snowpark-python"
62
+ SNOWPARK_LIB_REGEX = re.compile(
63
+ # support PEP 508, even though not all of it is supported in Snowflake yet
64
+ rf"'{SNOWPARK_LIB_NAME}\s*((<|<=|!=|==|>=|>|~=|===)\s*[a-zA-Z0-9_.*+!-]+)?'"
65
+ )
66
+ STAGE_PREFIX = "@"
67
+
68
+
69
+ def _determine_virtual_env(
70
+ project_root: Path, processor: ProcessorMapping
71
+ ) -> Dict[str, Any]:
72
+ """
73
+ Determines a virtual environment to run the Snowpark processor in, either through the project definition or by querying the current environment.
74
+ """
75
+ if (processor.properties is None) or ("env" not in processor.properties):
76
+ return {}
77
+
78
+ env_props = processor.properties["env"]
79
+ env_type = env_props.get("type", None)
80
+
81
+ if env_type is None:
82
+ return {}
83
+
84
+ if env_type.upper() == ExecutionEnvironmentType.CONDA.name:
85
+ env_name = env_props.get("name", None)
86
+ if env_name is None:
87
+ cc.warning(
88
+ "No name found in project definition file for the conda environment to run the Snowpark processor in. Will attempt to auto-detect the current conda environment."
89
+ )
90
+ return {"env_type": ExecutionEnvironmentType.CONDA, "name": env_name}
91
+ elif env_type.upper() == ExecutionEnvironmentType.VENV.name:
92
+ env_path_str = env_props.get("path", None)
93
+ if env_path_str is None:
94
+ cc.warning(
95
+ "No path found in project definition file for the conda environment to run the Snowpark processor in. Will attempt to auto-detect the current venv path."
96
+ )
97
+ env_path = None
98
+ else:
99
+ env_path = Path(env_path_str)
100
+ if not env_path.is_absolute():
101
+ env_path = project_root / env_path
102
+ return {
103
+ "env_type": ExecutionEnvironmentType.VENV,
104
+ "path": env_path,
105
+ }
106
+ elif env_type.upper() == ExecutionEnvironmentType.CURRENT.name:
107
+ return {
108
+ "env_type": ExecutionEnvironmentType.CURRENT,
109
+ }
110
+ return {}
111
+
112
+
113
+ def _is_python_file_artifact(src: Path, dest: Path):
114
+ return src.is_file() and src.suffix == ".py"
115
+
116
+
117
+ def _execute_in_sandbox(
118
+ py_file: str, deploy_root: Path, kwargs: Dict[str, Any]
119
+ ) -> Optional[List[Dict[str, Any]]]:
120
+ # Create the code snippet to be executed in the sandbox
121
+ script_source = jinja_render_from_file(
122
+ template_path=TEMPLATE_PATH, data={"py_file": py_file}
123
+ )
124
+
125
+ try:
126
+ completed_process = execute_script_in_sandbox(
127
+ script_source=script_source,
128
+ cwd=deploy_root,
129
+ timeout=DEFAULT_TIMEOUT,
130
+ **kwargs,
131
+ )
132
+ except SandboxExecutionError as sdbx_err:
133
+ cc.warning(
134
+ f"Could not fetch Snowpark objects from {py_file} due to {sdbx_err}, continuing execution for the rest of the python files."
135
+ )
136
+ return None
137
+ except Exception as err:
138
+ cc.warning(
139
+ f"Could not fetch Snowpark objects from {py_file} due to {err}, continuing execution for the rest of the python files."
140
+ )
141
+ return None
142
+
143
+ if completed_process.returncode != 0:
144
+ cc.warning(
145
+ f"Could not fetch Snowpark objects from {py_file} due to the following error:\n {completed_process.stderr}"
146
+ )
147
+ cc.warning("Continuing execution for the rest of the python files.")
148
+ return None
149
+
150
+ try:
151
+ return json.loads(completed_process.stdout)
152
+ except Exception as exc:
153
+ cc.warning(
154
+ f"Could not load JSON into python due to the following exception: {exc}"
155
+ )
156
+ cc.warning(f"Continuing execution for the rest of the python files.")
157
+ return None
158
+
159
+
160
+ class SnowparkAnnotationProcessor(ArtifactProcessor):
161
+ """
162
+ Built-in Processor to discover Snowpark-annotated objects in a given set of python files,
163
+ and generate SQL code for creation of extension functions based on those discovered objects.
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ na_project: NativeAppProjectModel,
169
+ ):
170
+ super().__init__(na_project=na_project)
171
+
172
+ def process(
173
+ self,
174
+ artifact_to_process: PathMapping,
175
+ processor_mapping: Optional[ProcessorMapping],
176
+ **kwargs,
177
+ ) -> None:
178
+ """
179
+ Collects code annotations from Snowpark python files containing extension functions and augments the existing
180
+ setup script with generated SQL that registers these functions.
181
+ """
182
+
183
+ bundle_map = BundleMap(
184
+ project_root=self._na_project.project_root,
185
+ deploy_root=self._na_project.deploy_root,
186
+ )
187
+ bundle_map.add(artifact_to_process)
188
+
189
+ collected_extension_functions_by_path = self.collect_extension_functions(
190
+ bundle_map, processor_mapping
191
+ )
192
+
193
+ collected_output = []
194
+ collected_sql_files: List[Path] = []
195
+ for py_file, extension_fns in sorted(
196
+ collected_extension_functions_by_path.items()
197
+ ):
198
+ sql_file = self.generate_new_sql_file_name(
199
+ py_file=py_file,
200
+ )
201
+ collected_sql_files.append(sql_file)
202
+ insert_newline = False
203
+ for extension_fn in extension_fns:
204
+ create_stmt = generate_create_sql_ddl_statement(extension_fn)
205
+ if create_stmt is None:
206
+ continue
207
+
208
+ relative_py_file = py_file.relative_to(bundle_map.deploy_root())
209
+
210
+ grant_statements = generate_grant_sql_ddl_statements(extension_fn)
211
+ if grant_statements is not None:
212
+ collected_output.append(grant_statements)
213
+
214
+ with open(sql_file, "a") as file:
215
+ if insert_newline:
216
+ file.write("\n")
217
+ insert_newline = True
218
+ file.write(
219
+ f"-- Generated by the Snowflake CLI from {relative_py_file}\n"
220
+ )
221
+ file.write(f"-- DO NOT EDIT\n")
222
+ file.write(create_stmt)
223
+ if grant_statements is not None:
224
+ file.write("\n")
225
+ file.write(grant_statements)
226
+
227
+ self.deannotate(py_file, extension_fns)
228
+
229
+ if collected_sql_files:
230
+ edit_setup_script_with_exec_imm_sql(
231
+ collected_sql_files=collected_sql_files,
232
+ deploy_root=bundle_map.deploy_root(),
233
+ generated_root=self._generated_root,
234
+ )
235
+
236
+ @property
237
+ def _generated_root(self):
238
+ return self._na_project.generated_root / "snowpark"
239
+
240
+ def _normalize_imports(
241
+ self,
242
+ extension_fn: NativeAppExtensionFunction,
243
+ py_file: Path,
244
+ deploy_root: Path,
245
+ ):
246
+ normalized_imports: Set[str] = set()
247
+ # Add the py_file, which is the source of the extension function
248
+ normalized_imports.add(f"/{to_stage_path(py_file)}")
249
+
250
+ for raw_import in extension_fn.imports:
251
+ if not Path(deploy_root, raw_import).exists():
252
+ # This should capture import_str of different forms: stagenames, malformed paths etc
253
+ # But this will also return True if import_str == "/". Regardless, we append it all to normalized_imports
254
+ cc.warning(
255
+ f"{raw_import} does not exist in the deploy root. Skipping validation of this import."
256
+ )
257
+
258
+ if raw_import.startswith(STAGE_PREFIX) or raw_import.startswith("/"):
259
+ normalized_imports.add(raw_import)
260
+ else:
261
+ normalized_imports.add(f"/{to_stage_path(Path(raw_import))}")
262
+
263
+ # To ensure order when running tests
264
+ sorted_imports = list(normalized_imports)
265
+ sorted_imports.sort()
266
+ extension_fn.imports = sorted_imports
267
+
268
+ def _normalize(
269
+ self,
270
+ extension_fn: NativeAppExtensionFunction,
271
+ py_file: Path,
272
+ deploy_root: Path,
273
+ ):
274
+ if extension_fn.name is None:
275
+ # The extension function was not named explicitly, use the name of the Python function object as its name
276
+ extension_fn.name = extension_fn.handler
277
+
278
+ # Compute the fully qualified handler
279
+ # If user defined their udf as @udf(lambda: x, ...) then extension_fn.handler is <lambda>.
280
+ extension_fn.handler = f"{py_file.stem}.{extension_fn.handler}"
281
+
282
+ extension_fn.packages = [
283
+ self._normalize_package_name(pkg) for pkg in extension_fn.packages
284
+ ]
285
+ snowpark_lib_name = ensure_string_literal(SNOWPARK_LIB_NAME)
286
+ if snowpark_lib_name not in extension_fn.packages:
287
+ extension_fn.packages.append(snowpark_lib_name)
288
+
289
+ if extension_fn.imports is None:
290
+ extension_fn.imports = []
291
+ self._normalize_imports(
292
+ extension_fn=extension_fn,
293
+ py_file=py_file,
294
+ deploy_root=deploy_root,
295
+ )
296
+
297
+ def _normalize_package_name(self, pkg: str) -> str:
298
+ """
299
+ Returns a normalized version of the provided package name, as a Snowflake SQL string literal. Since the
300
+ Snowpark library can sometimes add a spurious version to its own package name, we strip this here too so
301
+ that the native application does not accidentally rely on stale packages once the snowpark library is updated
302
+ in the cloud.
303
+
304
+ Args:
305
+ pkg (str): The package name to normalize.
306
+ Returns:
307
+ A normalized version of the package name, as a Snowflake SQL string literal.
308
+ """
309
+ normalized_package_name = ensure_string_literal(pkg.strip())
310
+ if SNOWPARK_LIB_REGEX.fullmatch(normalized_package_name):
311
+ return ensure_string_literal(SNOWPARK_LIB_NAME)
312
+ return normalized_package_name
313
+
314
+ def collect_extension_functions(
315
+ self, bundle_map: BundleMap, processor_mapping: Optional[ProcessorMapping]
316
+ ) -> Dict[Path, List[NativeAppExtensionFunction]]:
317
+ kwargs = (
318
+ _determine_virtual_env(self._na_project.project_root, processor_mapping)
319
+ if processor_mapping is not None
320
+ else {}
321
+ )
322
+
323
+ collected_extension_fns_by_path: Dict[
324
+ Path, List[NativeAppExtensionFunction]
325
+ ] = {}
326
+
327
+ for src_file, dest_file in sorted(
328
+ bundle_map.all_mappings(
329
+ absolute=True,
330
+ expand_directories=True,
331
+ predicate=is_python_file_artifact,
332
+ )
333
+ ):
334
+ cc.step(
335
+ "Processing Snowpark annotations from {}".format(
336
+ dest_file.relative_to(bundle_map.deploy_root())
337
+ )
338
+ )
339
+ collected_extension_function_json = _execute_in_sandbox(
340
+ py_file=str(dest_file.resolve()),
341
+ deploy_root=self._na_project.deploy_root,
342
+ kwargs=kwargs,
343
+ )
344
+
345
+ if collected_extension_function_json is None:
346
+ continue
347
+
348
+ collected_extension_functions = []
349
+ for extension_function_json in collected_extension_function_json:
350
+ try:
351
+ extension_fn = NativeAppExtensionFunction(**extension_function_json)
352
+ self._normalize(
353
+ extension_fn,
354
+ py_file=dest_file.relative_to(bundle_map.deploy_root()),
355
+ deploy_root=bundle_map.deploy_root(),
356
+ )
357
+ collected_extension_functions.append(extension_fn)
358
+ except ValidationError:
359
+ cc.warning("Invalid extension function definition")
360
+
361
+ if collected_extension_functions:
362
+ collected_extension_fns_by_path[
363
+ dest_file
364
+ ] = collected_extension_functions
365
+
366
+ return collected_extension_fns_by_path
367
+
368
+ def generate_new_sql_file_name(self, py_file: Path) -> Path:
369
+ """
370
+ Generates a SQL filename for the generated root from the python file, and creates its parent directories.
371
+ """
372
+ relative_py_file = py_file.relative_to(self._na_project.deploy_root)
373
+ sql_file = Path(self._generated_root, relative_py_file.with_suffix(".sql"))
374
+ if sql_file.exists():
375
+ cc.warning(
376
+ f"""\
377
+ File {sql_file} already exists, will append SQL statements to this file.
378
+ """
379
+ )
380
+ sql_file.parent.mkdir(exist_ok=True, parents=True)
381
+ return sql_file
382
+
383
+ def deannotate(
384
+ self, py_file: Path, extension_fns: List[NativeAppExtensionFunction]
385
+ ):
386
+ with open(py_file, "r", encoding="utf-8") as f:
387
+ code = f.read()
388
+
389
+ if py_file.is_symlink():
390
+ # if the file is a symlink, make sure we don't overwrite the original
391
+ py_file.unlink()
392
+
393
+ new_code = deannotate_module_source(code, extension_fns)
394
+
395
+ with open(py_file, "w", encoding="utf-8") as f:
396
+ f.write(new_code)
397
+
398
+
399
+ def generate_create_sql_ddl_statement(
400
+ extension_fn: NativeAppExtensionFunction,
401
+ ) -> Optional[str]:
402
+ """
403
+ Generates a "CREATE FUNCTION/PROCEDURE ... " SQL DDL statement based on an extension function definition.
404
+ Logic for this create statement has been lifted from snowflake-snowpark-python v1.15.0 package.
405
+ """
406
+
407
+ object_type = get_sql_object_type(extension_fn)
408
+ if object_type is None:
409
+ cc.warning(f"Unsupported extension function type: {extension_fn.function_type}")
410
+ return None
411
+
412
+ arguments_in_sql = ", ".join(
413
+ [get_sql_argument_signature(arg) for arg in extension_fn.signature]
414
+ )
415
+
416
+ create_query = dedent(
417
+ f"""
418
+ CREATE OR REPLACE
419
+ {object_type} {get_qualified_object_name(extension_fn)}({arguments_in_sql})
420
+ RETURNS {extension_fn.returns}
421
+ LANGUAGE PYTHON
422
+ RUNTIME_VERSION={extension_fn.runtime}
423
+ """
424
+ ).strip()
425
+
426
+ if extension_fn.imports:
427
+ create_query += (
428
+ f"\nIMPORTS=({', '.join(ensure_all_string_literals(extension_fn.imports))})"
429
+ )
430
+
431
+ if extension_fn.packages:
432
+ create_query += f"\nPACKAGES=({', '.join(ensure_all_string_literals([pkg.strip() for pkg in extension_fn.packages]))})"
433
+
434
+ if extension_fn.external_access_integrations:
435
+ create_query += f"\nEXTERNAL_ACCESS_INTEGRATIONS=({', '.join(ensure_all_string_literals(extension_fn.external_access_integrations))})"
436
+
437
+ if extension_fn.secrets:
438
+ create_query += f"""\nSECRETS=({', '.join([f"{ensure_string_literal(k)}={v}" for k, v in extension_fn.secrets.items()])})"""
439
+
440
+ create_query += f"\nHANDLER={ensure_string_literal(extension_fn.handler)}"
441
+
442
+ if extension_fn.function_type == ExtensionFunctionTypeEnum.PROCEDURE:
443
+ if extension_fn.execute_as_caller:
444
+ create_query += f"\nEXECUTE AS CALLER"
445
+ else:
446
+ create_query += f"\nEXECUTE AS OWNER"
447
+ create_query += ";\n"
448
+
449
+ return create_query
450
+
451
+
452
+ def generate_grant_sql_ddl_statements(
453
+ extension_fn: NativeAppExtensionFunction,
454
+ ) -> Optional[str]:
455
+ """
456
+ Generates a "GRANT USAGE TO ... " SQL DDL statement based on a dictionary of extension function properties.
457
+ If no application roles are present, then the function returns None.
458
+ """
459
+
460
+ if not extension_fn.application_roles:
461
+ cc.warning(
462
+ f"Skipping generation of 'GRANT USAGE ON ...' SQL statement for {extension_fn.function_type.upper()} {extension_fn.handler} due to lack of application roles."
463
+ )
464
+ return None
465
+
466
+ grant_sql_statements = []
467
+ object_type = (
468
+ "PROCEDURE"
469
+ if extension_fn.function_type == ExtensionFunctionTypeEnum.PROCEDURE
470
+ else "FUNCTION"
471
+ )
472
+ for app_role in extension_fn.application_roles:
473
+ grant_sql_statement = dedent(
474
+ f"""\
475
+ GRANT USAGE ON {object_type} {get_qualified_object_name(extension_fn)}({get_function_type_signature_for_grant(extension_fn)})
476
+ TO APPLICATION ROLE {app_role};
477
+ """
478
+ ).strip()
479
+ grant_sql_statements.append(grant_sql_statement)
480
+
481
+ return "\n".join(grant_sql_statements)
482
+
483
+
484
+ def edit_setup_script_with_exec_imm_sql(
485
+ collected_sql_files: List[Path], deploy_root: Path, generated_root: Path
486
+ ):
487
+ """
488
+ Adds an 'execute immediate' to setup script for every SQL file in the map
489
+ """
490
+ # Create a __generated.sql in the __generated folder
491
+ generated_file_path = Path(generated_root, f"__generated.sql")
492
+ generated_file_path.parent.mkdir(exist_ok=True, parents=True)
493
+
494
+ if generated_file_path.exists():
495
+ cc.warning(
496
+ f"""\
497
+ File {generated_file_path} already exists.
498
+ Could not complete code generation of Snowpark Extension Functions.
499
+ """
500
+ )
501
+ return
502
+
503
+ # For every SQL file, add SQL statement 'execute immediate' to __generated.sql script.
504
+ with open(generated_file_path, "a") as file:
505
+ for sql_file in collected_sql_files:
506
+ sql_file_relative_path = sql_file.relative_to(
507
+ deploy_root
508
+ ) # Path on stage, without the leading slash
509
+ file.write(
510
+ f"EXECUTE IMMEDIATE FROM '/{to_stage_path(sql_file_relative_path)}';\n"
511
+ )
512
+
513
+ # Find the setup script in the deploy root.
514
+ setup_file_path = find_setup_script_file(deploy_root=deploy_root)
515
+ with open(setup_file_path, "r", encoding="utf-8") as file:
516
+ code = file.read()
517
+ # Unlink to prevent over-writing source file
518
+ if setup_file_path.is_symlink():
519
+ setup_file_path.unlink()
520
+
521
+ # Write original contents and the execute immediate sql to the setup script
522
+ generated_file_relative_path = generated_file_path.relative_to(deploy_root)
523
+ with open(setup_file_path, "w", encoding="utf-8") as file:
524
+ file.write(code)
525
+ file.write(
526
+ f"\nEXECUTE IMMEDIATE FROM '/{to_stage_path(generated_file_relative_path)}';"
527
+ )
528
+ file.write(f"\n")