snowflake-sqlalchemy 1.7.3__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 (39) hide show
  1. snowflake/sqlalchemy/__init__.py +162 -0
  2. snowflake/sqlalchemy/_constants.py +14 -0
  3. snowflake/sqlalchemy/base.py +1188 -0
  4. snowflake/sqlalchemy/compat.py +36 -0
  5. snowflake/sqlalchemy/custom_commands.py +627 -0
  6. snowflake/sqlalchemy/custom_types.py +155 -0
  7. snowflake/sqlalchemy/exc.py +82 -0
  8. snowflake/sqlalchemy/functions.py +16 -0
  9. snowflake/sqlalchemy/parser/custom_type_parser.py +245 -0
  10. snowflake/sqlalchemy/provision.py +12 -0
  11. snowflake/sqlalchemy/requirements.py +313 -0
  12. snowflake/sqlalchemy/snowdialect.py +1029 -0
  13. snowflake/sqlalchemy/sql/__init__.py +3 -0
  14. snowflake/sqlalchemy/sql/custom_schema/__init__.py +9 -0
  15. snowflake/sqlalchemy/sql/custom_schema/clustered_table.py +37 -0
  16. snowflake/sqlalchemy/sql/custom_schema/custom_table_base.py +127 -0
  17. snowflake/sqlalchemy/sql/custom_schema/custom_table_prefix.py +13 -0
  18. snowflake/sqlalchemy/sql/custom_schema/dynamic_table.py +117 -0
  19. snowflake/sqlalchemy/sql/custom_schema/hybrid_table.py +63 -0
  20. snowflake/sqlalchemy/sql/custom_schema/iceberg_table.py +102 -0
  21. snowflake/sqlalchemy/sql/custom_schema/options/__init__.py +33 -0
  22. snowflake/sqlalchemy/sql/custom_schema/options/as_query_option.py +63 -0
  23. snowflake/sqlalchemy/sql/custom_schema/options/cluster_by_option.py +58 -0
  24. snowflake/sqlalchemy/sql/custom_schema/options/identifier_option.py +63 -0
  25. snowflake/sqlalchemy/sql/custom_schema/options/invalid_table_option.py +25 -0
  26. snowflake/sqlalchemy/sql/custom_schema/options/keyword_option.py +65 -0
  27. snowflake/sqlalchemy/sql/custom_schema/options/keywords.py +14 -0
  28. snowflake/sqlalchemy/sql/custom_schema/options/literal_option.py +67 -0
  29. snowflake/sqlalchemy/sql/custom_schema/options/table_option.py +84 -0
  30. snowflake/sqlalchemy/sql/custom_schema/options/target_lag_option.py +94 -0
  31. snowflake/sqlalchemy/sql/custom_schema/snowflake_table.py +70 -0
  32. snowflake/sqlalchemy/sql/custom_schema/table_from_query.py +54 -0
  33. snowflake/sqlalchemy/util.py +344 -0
  34. snowflake/sqlalchemy/version.py +6 -0
  35. snowflake_sqlalchemy-1.7.3.dist-info/METADATA +737 -0
  36. snowflake_sqlalchemy-1.7.3.dist-info/RECORD +39 -0
  37. snowflake_sqlalchemy-1.7.3.dist-info/WHEEL +4 -0
  38. snowflake_sqlalchemy-1.7.3.dist-info/entry_points.txt +2 -0
  39. snowflake_sqlalchemy-1.7.3.dist-info/licenses/LICENSE.txt +202 -0
@@ -0,0 +1,737 @@
1
+ Metadata-Version: 2.4
2
+ Name: snowflake-sqlalchemy
3
+ Version: 1.7.3
4
+ Summary: Snowflake SQLAlchemy Dialect
5
+ Project-URL: Changelog, https://github.com/snowflakedb/snowflake-sqlalchemy/blob/main/DESCRIPTION.md
6
+ Project-URL: Documentation, https://docs.snowflake.com/en/user-guide/sqlalchemy.html
7
+ Project-URL: Homepage, https://www.snowflake.com/
8
+ Project-URL: Issues, https://github.com/snowflakedb/snowflake-sqlalchemy/issues
9
+ Project-URL: Source, https://github.com/snowflakedb/snowflake-sqlalchemy
10
+ Author-email: "Snowflake Inc." <triage-snowpark-python-api-dl@snowflake.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE.txt
13
+ Keywords: Snowflake,analytics,cloud,database,db,warehouse
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Environment :: Console
16
+ Classifier: Environment :: Other Environment
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: Education
19
+ Classifier: Intended Audience :: Information Technology
20
+ Classifier: Intended Audience :: System Administrators
21
+ Classifier: License :: OSI Approved :: Apache Software License
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Programming Language :: Python :: 3
24
+ Classifier: Programming Language :: Python :: 3 :: Only
25
+ Classifier: Programming Language :: Python :: 3.8
26
+ Classifier: Programming Language :: Python :: 3.9
27
+ Classifier: Programming Language :: Python :: 3.10
28
+ Classifier: Programming Language :: Python :: 3.11
29
+ Classifier: Programming Language :: Python :: 3.12
30
+ Classifier: Programming Language :: SQL
31
+ Classifier: Topic :: Database
32
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
33
+ Classifier: Topic :: Software Development
34
+ Classifier: Topic :: Software Development :: Libraries
35
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
36
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
37
+ Requires-Python: >=3.8
38
+ Requires-Dist: snowflake-connector-python<4.0.0
39
+ Requires-Dist: sqlalchemy>=1.4.19
40
+ Provides-Extra: development
41
+ Requires-Dist: mock; extra == 'development'
42
+ Requires-Dist: numpy; extra == 'development'
43
+ Requires-Dist: pre-commit; extra == 'development'
44
+ Requires-Dist: pytest; extra == 'development'
45
+ Requires-Dist: pytest-cov; extra == 'development'
46
+ Requires-Dist: pytest-rerunfailures; extra == 'development'
47
+ Requires-Dist: pytest-timeout; extra == 'development'
48
+ Requires-Dist: pytz; extra == 'development'
49
+ Requires-Dist: setuptools; extra == 'development'
50
+ Requires-Dist: syrupy==4.6.1; extra == 'development'
51
+ Provides-Extra: pandas
52
+ Requires-Dist: snowflake-connector-python[pandas]; extra == 'pandas'
53
+ Description-Content-Type: text/markdown
54
+
55
+ # Snowflake SQLAlchemy
56
+
57
+ [![Build and Test](https://github.com/snowflakedb/snowflake-sqlalchemy/actions/workflows/build_test.yml/badge.svg)](https://github.com/snowflakedb/snowflake-sqlalchemy/actions/workflows/build_test.yml)
58
+ [![codecov](https://codecov.io/gh/snowflakedb/snowflake-sqlalchemy/branch/main/graph/badge.svg)](https://codecov.io/gh/snowflakedb/snowflake-sqlalchemy)
59
+ [![PyPi](https://img.shields.io/pypi/v/snowflake-sqlalchemy.svg)](https://pypi.python.org/pypi/snowflake-sqlalchemy/)
60
+ [![License Apache-2.0](https://img.shields.io/:license-Apache%202-brightgreen.svg)](http://www.apache.org/licenses/LICENSE-2.0.txt)
61
+ [![Codestyle Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
62
+
63
+ Snowflake SQLAlchemy runs on the top of the Snowflake Connector for Python as a [dialect](http://docs.sqlalchemy.org/en/latest/dialects/) to bridge a Snowflake database and SQLAlchemy applications.
64
+
65
+
66
+ | :exclamation: | For production-affecting or urgent issues related to the connector, please [create a case with Snowflake Support](https://community.snowflake.com/s/article/How-To-Submit-a-Support-Case-in-Snowflake-Lodge). |
67
+ |---------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
68
+
69
+
70
+ ## Prerequisites
71
+
72
+ ### Snowflake Connector for Python
73
+
74
+ The only requirement for Snowflake SQLAlchemy is the Snowflake Connector for Python; however, the connector does not need to be installed because installing Snowflake SQLAlchemy automatically installs the connector.
75
+
76
+ ### Data Analytics and Web Application Frameworks (Optional)
77
+
78
+ Snowflake SQLAlchemy can be used with [Pandas](http://pandas.pydata.org/), [Jupyter](http://jupyter.org/) and [Pyramid](http://www.pylonsproject.org/), which provide higher levels of application frameworks for data analytics and web applications. However, building a working environment from scratch is not a trivial task, particularly for novice users. Installing the frameworks requires C compilers and tools, and choosing the right tools and versions is a hurdle that might deter users from using Python applications.
79
+
80
+ An easier way to build an environment is through [Anaconda](https://www.continuum.io/why-anaconda), which provides a complete, precompiled technology stack for all users, including non-Python experts such as data analysts and students. For Anaconda installation instructions, see the [Anaconda install documentation](https://docs.continuum.io/anaconda/install). The Snowflake SQLAlchemy package can then be installed on top of Anaconda using [pip](https://pypi.python.org/pypi/pip).
81
+
82
+ ## Installing Snowflake SQLAlchemy
83
+
84
+ The Snowflake SQLAlchemy package can be installed from the public PyPI repository using `pip`:
85
+
86
+ ```shell
87
+ pip install --upgrade snowflake-sqlalchemy
88
+ ```
89
+
90
+ `pip` automatically installs all required modules, including the Snowflake Connector for Python.
91
+
92
+ ## Verifying Your Installation
93
+
94
+ 1. Create a file (e.g. `validate.py`) that contains the following Python sample code,
95
+ which connects to Snowflake and displays the Snowflake version:
96
+
97
+ ```python
98
+ from sqlalchemy import create_engine
99
+
100
+ engine = create_engine(
101
+ 'snowflake://{user}:{password}@{account}/'.format(
102
+ user='<your_user_login_name>',
103
+ password='<your_password>',
104
+ account='<your_account_name>',
105
+ )
106
+ )
107
+ try:
108
+ connection = engine.connect()
109
+ results = connection.execute('select current_version()').fetchone()
110
+ print(results[0])
111
+ finally:
112
+ connection.close()
113
+ engine.dispose()
114
+ ```
115
+
116
+ 2. Replace `<your_user_login_name>`, `<your_password>`, and `<your_account_name>` with the appropriate values for your Snowflake account and user.
117
+
118
+ For more details, see [Connection Parameters](#connection-parameters).
119
+
120
+ 3. Execute the sample code. For example, if you created a file named `validate.py`:
121
+
122
+ ```shell
123
+ python validate.py
124
+ ```
125
+
126
+ The Snowflake version (e.g. `1.48.0`) should be displayed.
127
+
128
+ ## Parameters and Behavior
129
+
130
+ As much as possible, Snowflake SQLAlchemy provides compatible functionality for SQLAlchemy applications. For information on using SQLAlchemy, see the [SQLAlchemy documentation](http://docs.sqlalchemy.org/en/latest/).
131
+
132
+ However, Snowflake SQLAlchemy also provides Snowflake-specific parameters and behavior, which are described in the following sections.
133
+
134
+ ### Connection Parameters
135
+
136
+ Snowflake SQLAlchemy uses the following syntax for the connection string used to connect to Snowflake and initiate a session:
137
+
138
+ ```python
139
+ 'snowflake://<user_login_name>:<password>@<account_name>'
140
+ ```
141
+
142
+ Where:
143
+
144
+ - `<user_login_name>` is the login name for your Snowflake user.
145
+ - `<password>` is the password for your Snowflake user.
146
+ - `<account_name>` is the name of your Snowflake account.
147
+
148
+ Include the region in the `<account_name>` if applicable, more info is available [here](https://docs.snowflake.com/en/user-guide/connecting.html#your-snowflake-account-name).
149
+
150
+ You can optionally specify the initial database and schema for the Snowflake session by including them at the end of the connection string, separated by `/`. You can also specify the initial warehouse and role for the session as a parameter string at the end of the connection string:
151
+
152
+ ```python
153
+ 'snowflake://<user_login_name>:<password>@<account_name>/<database_name>/<schema_name>?warehouse=<warehouse_name>&role=<role_name>'
154
+ ```
155
+
156
+ #### Escaping Special Characters such as `%, @` signs in Passwords
157
+
158
+ As pointed out in [SQLAlchemy](https://docs.sqlalchemy.org/en/14/core/engines.html#escaping-special-characters-such-as-signs-in-passwords), URLs
159
+ containing special characters need to be URL encoded to be parsed correctly. This includes the `%, @` signs. Unescaped password containing special
160
+ characters could lead to authentication failure.
161
+
162
+ The encoding for the password can be generated using `urllib.parse`:
163
+
164
+ ```python
165
+ import urllib.parse
166
+ urllib.parse.quote("kx@% jj5/g")
167
+ 'kx%40%25%20jj5/g'
168
+ ```
169
+
170
+ **Note**: `urllib.parse.quote_plus` may also be used if there is no space in the string, as `urllib.parse.quote_plus` will replace space with `+`.
171
+
172
+ To create an engine with the proper encodings, either manually constructing the url string by formatting
173
+ or taking advantage of the `snowflake.sqlalchemy.URL` helper method:
174
+
175
+ ```python
176
+ import urllib.parse
177
+ from snowflake.sqlalchemy import URL
178
+ from sqlalchemy import create_engine
179
+
180
+ quoted_password = urllib.parse.quote("kx@% jj5/g")
181
+
182
+ # 1. manually constructing an url string
183
+ url = f'snowflake://testuser1:{quoted_password}@abc123/testdb/public?warehouse=testwh&role=myrole'
184
+ engine = create_engine(url)
185
+
186
+ # 2. using the snowflake.sqlalchemy.URL helper method
187
+ engine = create_engine(URL(
188
+ account = 'abc123',
189
+ user = 'testuser1',
190
+ password = quoted_password,
191
+ database = 'testdb',
192
+ schema = 'public',
193
+ warehouse = 'testwh',
194
+ role='myrole',
195
+ ))
196
+ ```
197
+
198
+ **Note**:
199
+ After login, the initial database, schema, warehouse and role specified in the connection string can always be changed for the session.
200
+
201
+ The following example calls the `create_engine` method with the user name `testuser1`, password `0123456`, account name `abc123`, database `testdb`, schema `public`, warehouse `testwh`, and role `myrole`:
202
+
203
+ ```python
204
+ from sqlalchemy import create_engine
205
+ engine = create_engine(
206
+ 'snowflake://testuser1:0123456@abc123/testdb/public?warehouse=testwh&role=myrole'
207
+ )
208
+ ```
209
+
210
+ Other parameters, such as `timezone`, can also be specified as a URI parameter or in `connect_args` parameters. For example:
211
+
212
+ ```python
213
+ from sqlalchemy import create_engine
214
+ engine = create_engine(
215
+ 'snowflake://testuser1:0123456@abc123/testdb/public?warehouse=testwh&role=myrole',
216
+ connect_args={
217
+ 'timezone': 'America/Los_Angeles',
218
+ }
219
+ )
220
+ ```
221
+
222
+ For convenience, you can use the `snowflake.sqlalchemy.URL` method to construct the connection string and connect to the database. The following example constructs the same connection string from the previous example:
223
+
224
+ ```python
225
+ from snowflake.sqlalchemy import URL
226
+ from sqlalchemy import create_engine
227
+
228
+ engine = create_engine(URL(
229
+ account = 'abc123',
230
+ user = 'testuser1',
231
+ password = '0123456',
232
+ database = 'testdb',
233
+ schema = 'public',
234
+ warehouse = 'testwh',
235
+ role='myrole',
236
+ timezone = 'America/Los_Angeles',
237
+ ))
238
+ ```
239
+
240
+ #### Using a proxy server
241
+
242
+ Use the supported environment variables, `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` to configure a proxy server.
243
+
244
+ ### Opening and Closing Connection
245
+
246
+ Open a connection by executing `engine.connect()`; avoid using `engine.execute()`. Make certain to close the connection by executing `connection.close()` before
247
+ `engine.dispose()`; otherwise, the Python Garbage collector removes the resources required to communicate with Snowflake, preventing the Python connector from closing the session properly.
248
+
249
+ ```python
250
+ # Avoid this.
251
+ engine = create_engine(...)
252
+ engine.execute(<SQL>)
253
+ engine.dispose()
254
+
255
+ # Better.
256
+ engine = create_engine(...)
257
+ connection = engine.connect()
258
+ try:
259
+ connection.execute(text(<SQL>))
260
+ finally:
261
+ connection.close()
262
+ engine.dispose()
263
+
264
+ # Best
265
+ try:
266
+ with engine.connect() as connection:
267
+ connection.execute(text(<SQL>))
268
+ # or
269
+ connection.exec_driver_sql(<SQL>)
270
+ finally:
271
+ engine.dispose()
272
+ ```
273
+
274
+ ### Auto-increment Behavior
275
+
276
+ Auto-incrementing a value requires the `Sequence` object. Include the `Sequence` object in the primary key column to automatically increment the value as each new record is inserted. For example:
277
+
278
+ ```python
279
+ t = Table('mytable', metadata,
280
+ Column('id', Integer, Sequence('id_seq'), primary_key=True),
281
+ Column(...), ...
282
+ )
283
+ ```
284
+
285
+ ### Object Name Case Handling
286
+
287
+ Snowflake stores all case-insensitive object names in uppercase text. In contrast, SQLAlchemy considers all lowercase object names to be case-insensitive. Snowflake SQLAlchemy converts the object name case during schema-level communication, i.e. during table and index reflection. If you use uppercase object names, SQLAlchemy assumes they are case-sensitive and encloses the names with quotes. This behavior will cause mismatches against data dictionary data received from Snowflake, so unless identifier names have been truly created as case sensitive using quotes, e.g., `"TestDb"`, all lowercase names should be used on the SQLAlchemy side.
288
+
289
+ ### Index Support
290
+
291
+ Indexes are supported only for Hybrid Tables in Snowflake SQLAlchemy. For more details on limitations and use cases, refer to the [Create Index documentation](https://docs.snowflake.com/en/sql-reference/constraints-indexes.html). You can create an index using the following methods:
292
+
293
+ #### Single Column Index
294
+
295
+ You can create a single column index by setting the `index=True` parameter on the column or by explicitly defining an `Index` object.
296
+
297
+ ```python
298
+ hybrid_test_table_1 = HybridTable(
299
+ "table_name",
300
+ metadata,
301
+ Column("column1", Integer, primary_key=True),
302
+ Column("column2", String, index=True),
303
+ Index("index_1", "column1", "column2")
304
+ )
305
+
306
+ metadata.create_all(engine_testaccount)
307
+ ```
308
+
309
+ #### Multi-Column Index
310
+
311
+ For multi-column indexes, you define the `Index` object specifying the columns that should be indexed.
312
+
313
+ ```python
314
+ hybrid_test_table_1 = HybridTable(
315
+ "table_name",
316
+ metadata,
317
+ Column("column1", Integer, primary_key=True),
318
+ Column("column2", String),
319
+ Index("index_1", "column1", "column2")
320
+ )
321
+
322
+ metadata.create_all(engine_testaccount)
323
+ ```
324
+
325
+ ### Numpy Data Type Support
326
+
327
+ Snowflake SQLAlchemy supports binding and fetching `NumPy` data types. Binding is always supported. To enable fetching `NumPy` data types, add `numpy=True` to the connection parameters.
328
+
329
+ The following example shows the round trip of `numpy.datetime64` data:
330
+
331
+ ```python
332
+ import numpy as np
333
+ import pandas as pd
334
+ engine = create_engine(URL(
335
+ account = 'abc123',
336
+ user = 'testuser1',
337
+ password = 'pass',
338
+ database = 'db',
339
+ schema = 'public',
340
+ warehouse = 'testwh',
341
+ role='myrole',
342
+ numpy=True,
343
+ ))
344
+
345
+ specific_date = np.datetime64('2016-03-04T12:03:05.123456789Z')
346
+
347
+ with engine.connect() as connection:
348
+ connection.exec_driver_sql(
349
+ "CREATE OR REPLACE TABLE ts_tbl(c1 TIMESTAMP_NTZ)")
350
+ connection.exec_driver_sql(
351
+ "INSERT INTO ts_tbl(c1) values(%s)", (specific_date,)
352
+ )
353
+ df = pd.read_sql_query("SELECT * FROM ts_tbl", connection)
354
+ assert df.c1.values[0] == specific_date
355
+ ```
356
+
357
+ The following `NumPy` data types are supported:
358
+
359
+ - numpy.int64
360
+ - numpy.float64
361
+ - numpy.datatime64
362
+
363
+ ### Cache Column Metadata
364
+
365
+ SQLAlchemy provides [the runtime inspection API](http://docs.sqlalchemy.org/en/latest/core/inspection.html) to get the runtime information about the various objects. One of the common use case is get all tables and their column metadata in a schema in order to construct a schema catalog. For example, [alembic](http://alembic.zzzcomputing.com/) on top of SQLAlchemy manages database schema migrations. A pseudo code flow is as follows:
366
+
367
+ ```python
368
+ inspector = inspect(engine)
369
+ schema = inspector.default_schema_name
370
+ for table_name in inspector.get_table_names(schema):
371
+ column_metadata = inspector.get_columns(table_name, schema)
372
+ primary_keys = inspector.get_pk_constraint(table_name, schema)
373
+ foreign_keys = inspector.get_foreign_keys(table_name, schema)
374
+ ...
375
+ ```
376
+
377
+ In this flow, a potential problem is it may take quite a while as queries run on each table. The results are cached but getting column metadata is expensive.
378
+
379
+ To mitigate the problem, Snowflake SQLAlchemy takes a flag `cache_column_metadata=True` such that all of column metadata for all tables are cached when `get_table_names` is called and the rest of `get_columns`, `get_primary_keys` and `get_foreign_keys` can take advantage of the cache.
380
+
381
+ ```python
382
+ engine = create_engine(URL(
383
+ account = 'abc123',
384
+ user = 'testuser1',
385
+ password = 'pass',
386
+ database = 'db',
387
+ schema = 'public',
388
+ warehouse = 'testwh',
389
+ role='myrole',
390
+ cache_column_metadata=True,
391
+ ))
392
+ ```
393
+
394
+ Note that this flag has been deprecated, as our caching now uses the built-in SQLAlchemy reflection cache, the flag has been removed, but caching has been improved and if possible extra data will be fetched and cached.
395
+
396
+ ### VARIANT, ARRAY and OBJECT Support
397
+
398
+ Snowflake SQLAlchemy supports fetching `VARIANT`, `ARRAY` and `OBJECT` data types. All types are converted into `str` in Python so that you can convert them to native data types using `json.loads`.
399
+
400
+ This example shows how to create a table including `VARIANT`, `ARRAY`, and `OBJECT` data type columns.
401
+
402
+ ```python
403
+ from snowflake.sqlalchemy import (VARIANT, ARRAY, OBJECT)
404
+
405
+ t = Table('my_semi_strucutred_datatype_table', metadata,
406
+ Column('va', VARIANT),
407
+ Column('ob', OBJECT),
408
+ Column('ar', ARRAY))
409
+ metdata.create_all(engine)
410
+ ```
411
+
412
+ In order to retrieve `VARIANT`, `ARRAY`, and `OBJECT` data type columns and convert them to the native Python data types, fetch data and call the `json.loads` method as follows:
413
+
414
+ ```python
415
+ import json
416
+ connection = engine.connect()
417
+ results = connection.execute(select([t])
418
+ row = results.fetchone()
419
+ data_variant = json.loads(row[0])
420
+ data_object = json.loads(row[1])
421
+ data_array = json.loads(row[2])
422
+ ```
423
+
424
+ ### Structured Data Types Support
425
+
426
+ This module defines custom SQLAlchemy types for Snowflake structured data, specifically for **Iceberg tables**.
427
+ The types —**MAP**, **OBJECT**, and **ARRAY**— allow you to store complex data structures in your SQLAlchemy models.
428
+ For detailed information, refer to the Snowflake [Structured data types](https://docs.snowflake.com/en/sql-reference/data-types-structured) documentation.
429
+
430
+ ---
431
+
432
+ #### MAP
433
+
434
+ The `MAP` type represents a collection of key-value pairs, where each key and value can have different types.
435
+
436
+ - **Key Type**: The type of the keys (e.g., `TEXT`, `NUMBER`).
437
+ - **Value Type**: The type of the values (e.g., `TEXT`, `NUMBER`).
438
+ - **Not Null**: Whether `NULL` values are allowed (default is `False`).
439
+
440
+ *Example Usage*
441
+
442
+ ```python
443
+ IcebergTable(
444
+ table_name,
445
+ metadata,
446
+ Column("id", Integer, primary_key=True),
447
+ Column("map_col", MAP(NUMBER(10, 0), TEXT(16777216))),
448
+ external_volume="external_volume",
449
+ base_location="base_location",
450
+ )
451
+ ```
452
+
453
+ #### OBJECT
454
+
455
+ The `OBJECT` type represents a semi-structured object with named fields. Each field can have a specific type, and you can also specify whether each field is nullable.
456
+
457
+ - **Items Types**: A dictionary of field names and their types. The type can optionally include a nullable flag (`True` for not nullable, `False` for nullable, default is `False`).
458
+
459
+ *Example Usage*
460
+
461
+ ```python
462
+ IcebergTable(
463
+ table_name,
464
+ metadata,
465
+ Column("id", Integer, primary_key=True),
466
+ Column(
467
+ "object_col",
468
+ OBJECT(key1=(TEXT(16777216), False), key2=(NUMBER(10, 0), False)),
469
+ OBJECT(key1=TEXT(16777216), key2=NUMBER(10, 0)), # Without nullable flag
470
+ ),
471
+ external_volume="external_volume",
472
+ base_location="base_location",
473
+ )
474
+ ```
475
+
476
+ #### ARRAY
477
+
478
+ The `ARRAY` type represents an ordered list of values, where each element has the same type. The type of the elements is defined when creating the array.
479
+
480
+ - **Value Type**: The type of the elements in the array (e.g., `TEXT`, `NUMBER`).
481
+ - **Not Null**: Whether `NULL` values are allowed (default is `False`).
482
+
483
+ *Example Usage*
484
+
485
+ ```python
486
+ IcebergTable(
487
+ table_name,
488
+ metadata,
489
+ Column("id", Integer, primary_key=True),
490
+ Column("array_col", ARRAY(TEXT(16777216))),
491
+ external_volume="external_volume",
492
+ base_location="base_location",
493
+ )
494
+ ```
495
+
496
+
497
+ ### CLUSTER BY Support
498
+
499
+ Snowflake SQLAchemy supports the `CLUSTER BY` parameter for tables. For information about the parameter, see :doc:`/sql-reference/sql/create-table`.
500
+
501
+ This example shows how to create a table with two columns, `id` and `name`, as the clustering keys:
502
+
503
+ ```python
504
+ t = Table('myuser', metadata,
505
+ Column('id', Integer, primary_key=True),
506
+ Column('name', String),
507
+ snowflake_clusterby=['id', 'name', text('id > 5')], ...
508
+ )
509
+ metadata.create_all(engine)
510
+ ```
511
+
512
+ ### Alembic Support
513
+
514
+ [Alembic](http://alembic.zzzcomputing.com) is a database migration tool on top of `SQLAlchemy`. Snowflake SQLAlchemy works by adding the following code to `alembic/env.py` so that Alembic can recognize Snowflake SQLAlchemy.
515
+
516
+ ```python
517
+ from alembic.ddl.impl import DefaultImpl
518
+
519
+ class SnowflakeImpl(DefaultImpl):
520
+ __dialect__ = 'snowflake'
521
+ ```
522
+
523
+ See [Alembic Documentation](http://alembic.zzzcomputing.com/) for general usage.
524
+
525
+ ### Key Pair Authentication Support
526
+
527
+ Snowflake SQLAlchemy supports key pair authentication by leveraging its Snowflake Connector for Python underpinnings. See [Using Key Pair Authentication](https://docs.snowflake.net/manuals/user-guide/python-connector-example.html#using-key-pair-authentication) for steps to create the private and public keys.
528
+
529
+ The private key parameter is passed through `connect_args` as follows:
530
+
531
+ ```python
532
+ ...
533
+ from snowflake.sqlalchemy import URL
534
+ from sqlalchemy import create_engine
535
+
536
+ from cryptography.hazmat.backends import default_backend
537
+ from cryptography.hazmat.primitives.asymmetric import rsa
538
+ from cryptography.hazmat.primitives.asymmetric import dsa
539
+ from cryptography.hazmat.primitives import serialization
540
+
541
+ with open("rsa_key.p8", "rb") as key:
542
+ p_key= serialization.load_pem_private_key(
543
+ key.read(),
544
+ password=os.environ['PRIVATE_KEY_PASSPHRASE'].encode(),
545
+ backend=default_backend()
546
+ )
547
+
548
+ pkb = p_key.private_bytes(
549
+ encoding=serialization.Encoding.DER,
550
+ format=serialization.PrivateFormat.PKCS8,
551
+ encryption_algorithm=serialization.NoEncryption())
552
+
553
+ engine = create_engine(URL(
554
+ account='abc123',
555
+ user='testuser1',
556
+ ),
557
+ connect_args={
558
+ 'private_key': pkb,
559
+ },
560
+ )
561
+ ```
562
+
563
+ Where `PRIVATE_KEY_PASSPHRASE` is a passphrase to decrypt the private key file, `rsa_key.p8`.
564
+
565
+ Currently a private key parameter is not accepted by the `snowflake.sqlalchemy.URL` method.
566
+
567
+ ### Merge Command Support
568
+
569
+ Snowflake SQLAlchemy supports upserting with its `MergeInto` custom expression.
570
+ See [Merge](https://docs.snowflake.net/manuals/sql-reference/sql/merge.html) for full documentation.
571
+
572
+ Use it as follows:
573
+
574
+ ```python
575
+ from sqlalchemy.orm import sessionmaker
576
+ from sqlalchemy import MetaData, create_engine
577
+ from snowflake.sqlalchemy import MergeInto
578
+
579
+ engine = create_engine(db.url, echo=False)
580
+ session = sessionmaker(bind=engine)()
581
+ connection = engine.connect()
582
+
583
+ meta = MetaData()
584
+ meta.reflect(bind=session.bind)
585
+ t1 = meta.tables['t1']
586
+ t2 = meta.tables['t2']
587
+
588
+ merge = MergeInto(target=t1, source=t2, on=t1.c.t1key == t2.c.t2key)
589
+ merge.when_matched_then_delete().where(t2.c.marked == 1)
590
+ merge.when_matched_then_update().where(t2.c.isnewstatus == 1).values(val = t2.c.newval, status=t2.c.newstatus)
591
+ merge.when_matched_then_update().values(val=t2.c.newval)
592
+ merge.when_not_matched_then_insert().values(val=t2.c.newval, status=t2.c.newstatus)
593
+ connection.execute(merge)
594
+ ```
595
+
596
+ ### CopyIntoStorage Support
597
+
598
+ Snowflake SQLAlchemy supports saving tables/query results into different stages, as well as into Azure Containers and
599
+ AWS buckets with its custom `CopyIntoStorage` expression. See [Copy into](https://docs.snowflake.net/manuals/sql-reference/sql/copy-into-location.html)
600
+ for full documentation.
601
+
602
+ Use it as follows:
603
+
604
+ ```python
605
+ from sqlalchemy.orm import sessionmaker
606
+ from sqlalchemy import MetaData, create_engine
607
+ from snowflake.sqlalchemy import CopyIntoStorage, AWSBucket, CSVFormatter
608
+
609
+ engine = create_engine(db.url, echo=False)
610
+ session = sessionmaker(bind=engine)()
611
+ connection = engine.connect()
612
+
613
+ meta = MetaData()
614
+ meta.reflect(bind=session.bind)
615
+ users = meta.tables['users']
616
+
617
+ copy_into = CopyIntoStorage(from_=users,
618
+ into=AWSBucket.from_uri('s3://my_private_backup').encryption_aws_sse_kms('1234abcd-12ab-34cd-56ef-1234567890ab'),
619
+ formatter=CSVFormatter().null_if(['null', 'Null']))
620
+ connection.execute(copy_into)
621
+ ```
622
+
623
+ ### Iceberg Table with Snowflake Catalog support
624
+
625
+ Snowflake SQLAlchemy supports Iceberg Tables with the Snowflake Catalog, along with various related parameters. For detailed information about Iceberg Tables, refer to the Snowflake [CREATE ICEBERG](https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table-snowflake) documentation.
626
+
627
+ To create an Iceberg Table using Snowflake SQLAlchemy, you can define the table using the SQLAlchemy Core syntax as follows:
628
+
629
+ ```python
630
+ table = IcebergTable(
631
+ "myuser",
632
+ metadata,
633
+ Column("id", Integer, primary_key=True),
634
+ Column("name", String),
635
+ external_volume=external_volume_name,
636
+ base_location="my_iceberg_table",
637
+ as_query="SELECT * FROM table"
638
+ )
639
+ ```
640
+
641
+ Alternatively, you can define the table using a declarative approach:
642
+
643
+ ```python
644
+ class MyUser(Base):
645
+ __tablename__ = "myuser"
646
+
647
+ @classmethod
648
+ def __table_cls__(cls, name, metadata, *arg, **kw):
649
+ return IcebergTable(name, metadata, *arg, **kw)
650
+
651
+ __table_args__ = {
652
+ "external_volume": "my_external_volume",
653
+ "base_location": "my_iceberg_table",
654
+ "as_query": "SELECT * FROM table",
655
+ }
656
+
657
+ id = Column(Integer, primary_key=True)
658
+ name = Column(String)
659
+ ```
660
+
661
+ ### Hybrid Table support
662
+
663
+ Snowflake SQLAlchemy supports Hybrid Tables with indexes. For detailed information, refer to the Snowflake [CREATE HYBRID TABLE](https://docs.snowflake.com/en/sql-reference/sql/create-hybrid-table) documentation.
664
+
665
+ To create a Hybrid Table and add an index, you can use the SQLAlchemy Core syntax as follows:
666
+
667
+ ```python
668
+ table = HybridTable(
669
+ "myuser",
670
+ metadata,
671
+ Column("id", Integer, primary_key=True),
672
+ Column("name", String),
673
+ Index("idx_name", "name")
674
+ )
675
+ ```
676
+
677
+ Alternatively, you can define the table using the declarative approach:
678
+
679
+ ```python
680
+ class MyUser(Base):
681
+ __tablename__ = "myuser"
682
+
683
+ @classmethod
684
+ def __table_cls__(cls, name, metadata, *arg, **kw):
685
+ return HybridTable(name, metadata, *arg, **kw)
686
+
687
+ __table_args__ = (
688
+ Index("idx_name", "name"),
689
+ )
690
+
691
+ id = Column(Integer, primary_key=True)
692
+ name = Column(String)
693
+ ```
694
+
695
+ ### Dynamic Tables support
696
+
697
+ Snowflake SQLAlchemy supports Dynamic Tables. For detailed information, refer to the Snowflake [CREATE DYNAMIC TABLE](https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table) documentation.
698
+
699
+ To create a Dynamic Table, you can use the SQLAlchemy Core syntax as follows:
700
+
701
+ ```python
702
+ dynamic_test_table_1 = DynamicTable(
703
+ "dynamic_MyUser",
704
+ metadata,
705
+ Column("id", Integer),
706
+ Column("name", String),
707
+ target_lag=(1, TimeUnit.HOURS), # Additionally, you can use SnowflakeKeyword.DOWNSTREAM
708
+ warehouse='test_wh',
709
+ refresh_mode=SnowflakeKeyword.FULL,
710
+ as_query="SELECT id, name from MyUser;"
711
+ )
712
+ ```
713
+
714
+ Alternatively, you can define a table without columns using the SQLAlchemy `select()` construct:
715
+
716
+ ```python
717
+ dynamic_test_table_1 = DynamicTable(
718
+ "dynamic_MyUser",
719
+ metadata,
720
+ target_lag=(1, TimeUnit.HOURS),
721
+ warehouse='test_wh',
722
+ refresh_mode=SnowflakeKeyword.FULL,
723
+ as_query=select(MyUser.id, MyUser.name)
724
+ )
725
+ ```
726
+
727
+ ### Notes
728
+
729
+ - Defining a primary key in a Dynamic Table is not supported, meaning declarative tables don’t support Dynamic Tables.
730
+ - When using the `as_query` parameter with a string, you must explicitly define the columns. However, if you use the SQLAlchemy `select()` construct, you don’t need to explicitly define the columns.
731
+ - Direct data insertion into Dynamic Tables is not supported.
732
+
733
+
734
+ ## Support
735
+
736
+ Feel free to file an issue or submit a PR here for general cases. For official support, contact Snowflake support at:
737
+ <https://community.snowflake.com/s/article/How-To-Submit-a-Support-Case-in-Snowflake-Lodge>