databricks-sqlalchemy 0.0.1b1__py3-none-any.whl → 1.0.1__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.
CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Release History
2
+
3
+ # 1.0.1
4
+
5
+ - This is databricks-sqlalchemy plugin based on sqlalchemy v1 and has all the databricks-sql-python v2.9.6 needed sqlalchemy features
@@ -1,2 +1 @@
1
- def hello() -> str:
2
- return "world"
1
+ from databricks.sqlalchemy.dialect import DatabricksDialect
@@ -0,0 +1,340 @@
1
+ """This module's layout loosely follows example of SQLAlchemy's postgres dialect
2
+ """
3
+
4
+ import decimal, re, datetime
5
+ from dateutil.parser import parse
6
+
7
+ import sqlalchemy
8
+ from sqlalchemy import types, event
9
+ from sqlalchemy.engine import default, Engine
10
+ from sqlalchemy.exc import DatabaseError, SQLAlchemyError
11
+ from sqlalchemy.engine import reflection
12
+
13
+ from databricks import sql
14
+
15
+
16
+ from databricks.sqlalchemy.dialect.base import (
17
+ DatabricksDDLCompiler,
18
+ DatabricksIdentifierPreparer,
19
+ )
20
+ from databricks.sqlalchemy.dialect.compiler import DatabricksTypeCompiler
21
+
22
+ try:
23
+ import alembic
24
+ except ImportError:
25
+ pass
26
+ else:
27
+ from alembic.ddl import DefaultImpl
28
+
29
+ class DatabricksImpl(DefaultImpl):
30
+ __dialect__ = "databricks"
31
+
32
+
33
+ class DatabricksDecimal(types.TypeDecorator):
34
+ """Translates strings to decimals"""
35
+
36
+ impl = types.DECIMAL
37
+
38
+ def process_result_value(self, value, dialect):
39
+ if value is not None:
40
+ return decimal.Decimal(value)
41
+ else:
42
+ return None
43
+
44
+
45
+ class DatabricksTimestamp(types.TypeDecorator):
46
+ """Translates timestamp strings to datetime objects"""
47
+
48
+ impl = types.TIMESTAMP
49
+
50
+ def process_result_value(self, value, dialect):
51
+ return value
52
+
53
+ def adapt(self, impltype, **kwargs):
54
+ return self.impl
55
+
56
+
57
+ class DatabricksDate(types.TypeDecorator):
58
+ """Translates date strings to date objects"""
59
+
60
+ impl = types.DATE
61
+
62
+ def process_result_value(self, value, dialect):
63
+ return value
64
+
65
+ def adapt(self, impltype, **kwargs):
66
+ return self.impl
67
+
68
+
69
+ class DatabricksDialect(default.DefaultDialect):
70
+ """This dialect implements only those methods required to pass our e2e tests"""
71
+
72
+ # Possible attributes are defined here: https://docs.sqlalchemy.org/en/14/core/internals.html#sqlalchemy.engine.Dialect
73
+ name: str = "databricks"
74
+ driver: str = "databricks-sql-python"
75
+ default_schema_name: str = "default"
76
+
77
+ preparer = DatabricksIdentifierPreparer # type: ignore
78
+ type_compiler = DatabricksTypeCompiler
79
+ ddl_compiler = DatabricksDDLCompiler
80
+ supports_statement_cache: bool = True
81
+ supports_multivalues_insert: bool = True
82
+ supports_native_decimal: bool = True
83
+ supports_sane_rowcount: bool = False
84
+ non_native_boolean_check_constraint: bool = False
85
+
86
+ @classmethod
87
+ def dbapi(cls):
88
+ return sql
89
+
90
+ def create_connect_args(self, url):
91
+ # TODO: can schema be provided after HOST?
92
+ # Expected URI format is: databricks+thrift://token:dapi***@***.cloud.databricks.com?http_path=/sql/***
93
+
94
+ kwargs = {
95
+ "server_hostname": url.host,
96
+ "access_token": url.password,
97
+ "http_path": url.query.get("http_path"),
98
+ "catalog": url.query.get("catalog"),
99
+ "schema": url.query.get("schema"),
100
+ }
101
+
102
+ self.schema = kwargs["schema"]
103
+ self.catalog = kwargs["catalog"]
104
+
105
+ return [], kwargs
106
+
107
+ def get_columns(self, connection, table_name, schema=None, **kwargs):
108
+ """Return information about columns in `table_name`.
109
+
110
+ Given a :class:`_engine.Connection`, a string
111
+ `table_name`, and an optional string `schema`, return column
112
+ information as a list of dictionaries with these keys:
113
+
114
+ name
115
+ the column's name
116
+
117
+ type
118
+ [sqlalchemy.types#TypeEngine]
119
+
120
+ nullable
121
+ boolean
122
+
123
+ default
124
+ the column's default value
125
+
126
+ autoincrement
127
+ boolean
128
+
129
+ sequence
130
+ a dictionary of the form
131
+ {'name' : str, 'start' :int, 'increment': int, 'minvalue': int,
132
+ 'maxvalue': int, 'nominvalue': bool, 'nomaxvalue': bool,
133
+ 'cycle': bool, 'cache': int, 'order': bool}
134
+
135
+ Additional column attributes may be present.
136
+ """
137
+
138
+ _type_map = {
139
+ "boolean": types.Boolean,
140
+ "smallint": types.SmallInteger,
141
+ "int": types.Integer,
142
+ "bigint": types.BigInteger,
143
+ "float": types.Float,
144
+ "double": types.Float,
145
+ "string": types.String,
146
+ "varchar": types.String,
147
+ "char": types.String,
148
+ "binary": types.String,
149
+ "array": types.String,
150
+ "map": types.String,
151
+ "struct": types.String,
152
+ "uniontype": types.String,
153
+ "decimal": DatabricksDecimal,
154
+ "timestamp": DatabricksTimestamp,
155
+ "date": DatabricksDate,
156
+ }
157
+
158
+ with self.get_connection_cursor(connection) as cur:
159
+ resp = cur.columns(
160
+ catalog_name=self.catalog,
161
+ schema_name=schema or self.schema,
162
+ table_name=table_name,
163
+ ).fetchall()
164
+
165
+ columns = []
166
+
167
+ for col in resp:
168
+
169
+ # Taken from PyHive. This removes added type info from decimals and maps
170
+ _col_type = re.search(r"^\w+", col.TYPE_NAME).group(0)
171
+ this_column = {
172
+ "name": col.COLUMN_NAME,
173
+ "type": _type_map[_col_type.lower()],
174
+ "nullable": bool(col.NULLABLE),
175
+ "default": col.COLUMN_DEF,
176
+ "autoincrement": False if col.IS_AUTO_INCREMENT == "NO" else True,
177
+ }
178
+ columns.append(this_column)
179
+
180
+ return columns
181
+
182
+ def get_pk_constraint(self, connection, table_name, schema=None, **kw):
183
+ """Return information about the primary key constraint on
184
+ table_name`.
185
+
186
+ Given a :class:`_engine.Connection`, a string
187
+ `table_name`, and an optional string `schema`, return primary
188
+ key information as a dictionary with these keys:
189
+
190
+ constrained_columns
191
+ a list of column names that make up the primary key
192
+
193
+ name
194
+ optional name of the primary key constraint.
195
+
196
+ """
197
+ # TODO: implement this behaviour
198
+ return {"constrained_columns": []}
199
+
200
+ def get_foreign_keys(self, connection, table_name, schema=None, **kw):
201
+ """Return information about foreign_keys in `table_name`.
202
+
203
+ Given a :class:`_engine.Connection`, a string
204
+ `table_name`, and an optional string `schema`, return foreign
205
+ key information as a list of dicts with these keys:
206
+
207
+ name
208
+ the constraint's name
209
+
210
+ constrained_columns
211
+ a list of column names that make up the foreign key
212
+
213
+ referred_schema
214
+ the name of the referred schema
215
+
216
+ referred_table
217
+ the name of the referred table
218
+
219
+ referred_columns
220
+ a list of column names in the referred table that correspond to
221
+ constrained_columns
222
+ """
223
+ # TODO: Implement this behaviour
224
+ return []
225
+
226
+ def get_indexes(self, connection, table_name, schema=None, **kw):
227
+ """Return information about indexes in `table_name`.
228
+
229
+ Given a :class:`_engine.Connection`, a string
230
+ `table_name` and an optional string `schema`, return index
231
+ information as a list of dictionaries with these keys:
232
+
233
+ name
234
+ the index's name
235
+
236
+ column_names
237
+ list of column names in order
238
+
239
+ unique
240
+ boolean
241
+ """
242
+ # TODO: Implement this behaviour
243
+ return []
244
+
245
+ def get_table_names(self, connection, schema=None, **kwargs):
246
+ TABLE_NAME = 1
247
+ with self.get_connection_cursor(connection) as cur:
248
+ sql_str = "SHOW TABLES FROM {}".format(
249
+ ".".join([self.catalog, schema or self.schema])
250
+ )
251
+ data = cur.execute(sql_str).fetchall()
252
+ _tables = [i[TABLE_NAME] for i in data]
253
+
254
+ return _tables
255
+
256
+ def get_view_names(self, connection, schema=None, **kwargs):
257
+ VIEW_NAME = 1
258
+ with self.get_connection_cursor(connection) as cur:
259
+ sql_str = "SHOW VIEWS FROM {}".format(
260
+ ".".join([self.catalog, schema or self.schema])
261
+ )
262
+ data = cur.execute(sql_str).fetchall()
263
+ _tables = [i[VIEW_NAME] for i in data]
264
+
265
+ return _tables
266
+
267
+ def do_rollback(self, dbapi_connection):
268
+ # Databricks SQL Does not support transactions
269
+ pass
270
+
271
+ def has_table(
272
+ self, connection, table_name, schema=None, catalog=None, **kwargs
273
+ ) -> bool:
274
+ """SQLAlchemy docstrings say dialect providers must implement this method"""
275
+
276
+ _schema = schema or self.schema
277
+ _catalog = catalog or self.catalog
278
+
279
+ # DBR >12.x uses underscores in error messages
280
+ DBR_LTE_12_NOT_FOUND_STRING = "Table or view not found"
281
+ DBR_GT_12_NOT_FOUND_STRING = "TABLE_OR_VIEW_NOT_FOUND"
282
+
283
+ try:
284
+ res = connection.execute(
285
+ f"DESCRIBE TABLE {_catalog}.{_schema}.{table_name}"
286
+ )
287
+ return True
288
+ except DatabaseError as e:
289
+ if DBR_GT_12_NOT_FOUND_STRING in str(
290
+ e
291
+ ) or DBR_LTE_12_NOT_FOUND_STRING in str(e):
292
+ return False
293
+ else:
294
+ raise e
295
+
296
+ def get_connection_cursor(self, connection):
297
+ """Added for backwards compatibility with 1.3.x"""
298
+ if hasattr(connection, "_dbapi_connection"):
299
+ return connection._dbapi_connection.dbapi_connection.cursor()
300
+ elif hasattr(connection, "raw_connection"):
301
+ return connection.raw_connection().cursor()
302
+ elif hasattr(connection, "connection"):
303
+ return connection.connection.cursor()
304
+
305
+ raise SQLAlchemyError(
306
+ "Databricks dialect can't obtain a cursor context manager from the dbapi"
307
+ )
308
+
309
+ @reflection.cache
310
+ def get_schema_names(self, connection, **kw):
311
+ # Equivalent to SHOW DATABASES
312
+
313
+ # TODO: replace with call to cursor.schemas() once its performance matches raw SQL
314
+ return [row[0] for row in connection.execute("SHOW SCHEMAS")]
315
+
316
+
317
+ @event.listens_for(Engine, "do_connect")
318
+ def receive_do_connect(dialect, conn_rec, cargs, cparams):
319
+ """Helpful for DS on traffic from clients using SQLAlchemy in particular"""
320
+
321
+ # Ignore connect invocations that don't use our dialect
322
+ if not dialect.name == "databricks":
323
+ return
324
+
325
+ if "_user_agent_entry" in cparams:
326
+ new_user_agent = f"sqlalchemy + {cparams['_user_agent_entry']}"
327
+ else:
328
+ new_user_agent = "sqlalchemy"
329
+
330
+ cparams["_user_agent_entry"] = new_user_agent
331
+
332
+ if sqlalchemy.__version__.startswith("1.3"):
333
+ # SQLAlchemy 1.3.x fails to parse the http_path, catalog, and schema from our connection string
334
+ # These should be passed in as connect_args when building the Engine
335
+
336
+ if "schema" in cparams:
337
+ dialect.schema = cparams["schema"]
338
+
339
+ if "catalog" in cparams:
340
+ dialect.catalog = cparams["catalog"]
@@ -0,0 +1,17 @@
1
+ import re
2
+ from sqlalchemy.sql import compiler
3
+
4
+
5
+ class DatabricksIdentifierPreparer(compiler.IdentifierPreparer):
6
+ # SparkSQL identifier specification:
7
+ # ref: https://spark.apache.org/docs/latest/sql-ref-identifier.html
8
+
9
+ legal_characters = re.compile(r"^[A-Z0-9_]+$", re.I)
10
+
11
+ def __init__(self, dialect):
12
+ super().__init__(dialect, initial_quote="`")
13
+
14
+
15
+ class DatabricksDDLCompiler(compiler.DDLCompiler):
16
+ def post_create_table(self, table):
17
+ return " USING DELTA"
@@ -0,0 +1,38 @@
1
+ from sqlalchemy.sql import compiler
2
+
3
+
4
+ class DatabricksTypeCompiler(compiler.GenericTypeCompiler):
5
+ """Originally forked from pyhive"""
6
+
7
+ def visit_INTEGER(self, type_):
8
+ return "INT"
9
+
10
+ def visit_NUMERIC(self, type_):
11
+ return "DECIMAL"
12
+
13
+ def visit_CHAR(self, type_):
14
+ return "STRING"
15
+
16
+ def visit_VARCHAR(self, type_):
17
+ return "STRING"
18
+
19
+ def visit_NCHAR(self, type_):
20
+ return "STRING"
21
+
22
+ def visit_TEXT(self, type_):
23
+ return "STRING"
24
+
25
+ def visit_CLOB(self, type_):
26
+ return "STRING"
27
+
28
+ def visit_BLOB(self, type_):
29
+ return "BINARY"
30
+
31
+ def visit_TIME(self, type_):
32
+ return "TIMESTAMP"
33
+
34
+ def visit_DATE(self, type_):
35
+ return "DATE"
36
+
37
+ def visit_DATETIME(self, type_):
38
+ return "TIMESTAMP"
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 Databricks, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.1
2
+ Name: databricks-sqlalchemy
3
+ Version: 1.0.1
4
+ Summary: Databricks SQLAlchemy plugin for Python
5
+ License: Apache-2.0
6
+ Author: Databricks
7
+ Author-email: databricks-sql-connector-maintainers@databricks.com
8
+ Requires-Python: >=3.8.0,<4.0.0
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Requires-Dist: databricks_sql_connector_core (>=4.0.0)
17
+ Requires-Dist: sqlalchemy (>=1.3.24,<2.0.0)
18
+ Project-URL: Bug Tracker, https://github.com/databricks/databricks-sqlalchemy/issues
19
+ Project-URL: Homepage, https://github.com/databricks/databricks-sqlalchemy
20
+ Description-Content-Type: text/markdown
21
+
22
+ ## Databricks dialect for SQLALchemy 1.0
23
+
24
+ The Databricks dialect for SQLAlchemy serves as bridge between [SQLAlchemy](https://www.sqlalchemy.org/) and the Databricks SQL Python driver. A working example demonstrating usage can be found in `example.py`.
25
+
26
+
27
+ ## Installation
28
+
29
+ To install the dialect and its dependencies:
30
+
31
+ ```shell
32
+ pip install databricks-sqlalchemy~=1.0
33
+ ```
34
+
35
+ If you also plan to use `alembic` you can alternatively run:
36
+
37
+ ```shell
38
+ pip install alembic
39
+ ```
40
+
41
+ ## Connection String
42
+
43
+ Every SQLAlchemy application that connects to a database needs to use an [Engine](https://docs.sqlalchemy.org/en/20/tutorial/engine.html#tutorial-engine), which you can create by passing a connection string to `create_engine`. The connection string must include these components:
44
+
45
+ 1. Host
46
+ 2. HTTP Path for a compute resource
47
+ 3. API access token
48
+ 4. Initial catalog for the connection
49
+ 5. Initial schema for the connection
50
+
51
+ **Note: Our dialect is built and tested on workspaces with Unity Catalog enabled. Support for the `hive_metastore` catalog is untested.**
52
+
53
+ For example:
54
+
55
+ ```python
56
+ import os
57
+ from sqlalchemy import create_engine
58
+
59
+ host = os.getenv("DATABRICKS_SERVER_HOSTNAME")
60
+ http_path = os.getenv("DATABRICKS_HTTP_PATH")
61
+ access_token = os.getenv("DATABRICKS_TOKEN")
62
+ catalog = os.getenv("DATABRICKS_CATALOG")
63
+ schema = os.getenv("DATABRICKS_SCHEMA")
64
+
65
+ if sqlalchemy.__version__.startswith("1.3"):
66
+ # SQLAlchemy 1.3.x fails to parse the http_path, catalog, and schema from our connection string
67
+ # Pass these in as connect_args instead
68
+
69
+ conn_string = f"databricks://token:{access_token}@{host}"
70
+ connect_args = dict(catalog=catalog, schema=schema, http_path=http_path)
71
+ all_connect_args = {**extra_connect_args, **connect_args}
72
+ engine = create_engine(conn_string, connect_args=all_connect_args)
73
+ else:
74
+ engine = create_engine(
75
+ f"databricks://token:{access_token}@{host}?http_path={http_path}&catalog={catalog}&schema={schema}",
76
+ connect_args=extra_connect_args,
77
+ )
78
+
79
+ ```
80
+
81
+ ## Types
82
+
83
+ The [SQLAlchemy type hierarchy](https://docs.sqlalchemy.org/en/13/core/type_basics.html) contains backend-agnostic type implementations (represented in CamelCase) and backend-specific types (represented in UPPERCASE). The majority of SQLAlchemy's [CamelCase](https://docs.sqlalchemy.org/en/13/core/type_basics.html#the-camelcase-datatypes) types are supported. This means that a SQLAlchemy application using these types should "just work" with Databricks.
84
+
85
+ |SQLAlchemy Type|Databricks SQL Type|
86
+ |-|-|
87
+ [`BigInteger`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.BigInteger)| [`BIGINT`](https://docs.databricks.com/en/sql/language-manual/data-types/bigint-type.html)
88
+ [`LargeBinary`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.LargeBinary)| (not supported)|
89
+ [`Boolean`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Boolean)| [`BOOLEAN`](https://docs.databricks.com/en/sql/language-manual/data-types/boolean-type.html)
90
+ [`Date`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Date)| [`DATE`](https://docs.databricks.com/en/sql/language-manual/data-types/date-type.html)
91
+ [`DateTime`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.DateTime)| [`TIMESTAMP_NTZ`](https://docs.databricks.com/en/sql/language-manual/data-types/timestamp-ntz-type.html)|
92
+ [`Enum`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Enum)| (not supported)|
93
+ [`Float`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Float)| [`FLOAT`](https://docs.databricks.com/en/sql/language-manual/data-types/float-type.html)
94
+ [`Integer`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Integer)| [`INT`](https://docs.databricks.com/en/sql/language-manual/data-types/int-type.html)
95
+ [`Numeric`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Numeric)| [`DECIMAL`](https://docs.databricks.com/en/sql/language-manual/data-types/decimal-type.html)|
96
+ [`PickleType`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.PickleType)| (not supported)|
97
+ [`SmallInteger`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.SmallInteger)| [`SMALLINT`](https://docs.databricks.com/en/sql/language-manual/data-types/smallint-type.html)
98
+ [`String`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.String)| [`STRING`](https://docs.databricks.com/en/sql/language-manual/data-types/string-type.html)|
99
+ [`Text`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Text)| [`STRING`](https://docs.databricks.com/en/sql/language-manual/data-types/string-type.html)|
100
+ [`Time`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Time)| [`STRING`](https://docs.databricks.com/en/sql/language-manual/data-types/string-type.html)|
101
+ [`Unicode`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Unicode)| [`STRING`](https://docs.databricks.com/en/sql/language-manual/data-types/string-type.html)|
102
+ [`UnicodeText`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.UnicodeText)| [`STRING`](https://docs.databricks.com/en/sql/language-manual/data-types/string-type.html)|
103
+ [`Uuid`](https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.Uuid)| [`STRING`](https://docs.databricks.com/en/sql/language-manual/data-types/string-type.html)
104
+
105
+
106
+ ### `LargeBinary()` and `PickleType()`
107
+
108
+ Databricks Runtime doesn't currently support binding of binary values in SQL queries, which is a pre-requisite for this functionality in SQLAlchemy.
109
+
110
+ ## `Enum()` and `CHECK` constraints
111
+
112
+ Support for `CHECK` constraints is not implemented in this dialect. Support is planned for a future release.
113
+
114
+ SQLAlchemy's `Enum()` type depends on `CHECK` constraints and is therefore not yet supported.
115
+
116
+
117
+ ### `String()`, `Text()`, `Unicode()`, and `UnicodeText()`
118
+
119
+ Databricks Runtime doesn't support length limitations for `STRING` fields. Therefore `String()` or `String(1)` or `String(255)` will all produce identical DDL. Since `Text()`, `Unicode()`, `UnicodeText()` all use the same underlying type in Databricks SQL, they will generate equivalent DDL.
120
+
121
+ ### `Time()`
122
+
123
+ Databricks Runtime doesn't have a native time-like data type. To implement this type in SQLAlchemy, our dialect stores SQLAlchemy `Time()` values in a `STRING` field. Unlike `DateTime` above, this type can optionally support timezone awareness (since the dialect is in complete control of the strings that we write to the Delta table).
124
+
125
+ ```python
126
+ from sqlalchemy import Time
127
+
128
+ class SomeModel(Base):
129
+ time_tz = Time(timezone=True)
130
+ time_ntz = Time()
131
+ ```
132
+
133
+
134
+ # Usage Notes
135
+
136
+ ## `Identity()` and `autoincrement`
137
+
138
+ Identity and generated value support is currently limited in this dialect.
139
+
140
+ When defining models, SQLAlchemy types can accept an [`autoincrement`](https://docs.sqlalchemy.org/en/13/core/metadata.html#sqlalchemy.schema.Column.params.autoincrement) argument. In our dialect, this argument is currently ignored. To create an auto-incrementing field in your model you can pass in an explicit [`Identity()`](https://docs.sqlalchemy.org/en/13/core/defaults.html#identity-ddl) instead.
141
+
142
+ Furthermore, in Databricks Runtime, only `BIGINT` fields can be configured to auto-increment. So in SQLAlchemy, you must use the `BigInteger()` type.
143
+
144
+ ```python
145
+ from sqlalchemy import Identity, String
146
+
147
+ class SomeModel(Base):
148
+ id = BigInteger(Identity())
149
+ value = String()
150
+ ```
151
+
152
+ When calling `Base.metadata.create_all()`, the executed DDL will include `GENERATED ALWAYS AS IDENTITY` for the `id` column. This is useful when using SQLAlchemy to generate tables. However, as of this writing, `Identity()` constructs are not captured when SQLAlchemy reflects a table's metadata (support for this is planned).
153
+
154
+ ## Usage with pandas
155
+
156
+ Use [`pandas.DataFrame.to_sql`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html) and [`pandas.read_sql`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html#pandas.read_sql) to write and read from Databricks SQL. These methods both accept a SQLAlchemy connection to interact with Databricks.
157
+
158
+ ### Read from Databricks SQL into pandas
159
+ ```python
160
+ from sqlalchemy import create_engine
161
+ import pandas as pd
162
+
163
+ engine = create_engine("databricks://token:dapi***@***.cloud.databricks.com?http_path=***&catalog=main&schema=test")
164
+ with engine.connect() as conn:
165
+ # This will read the contents of `main.test.some_table`
166
+ df = pd.read_sql("some_table", conn)
167
+ ```
168
+
169
+ ### Write to Databricks SQL from pandas
170
+
171
+ ```python
172
+ from sqlalchemy import create_engine
173
+ import pandas as pd
174
+
175
+ engine = create_engine("databricks://token:dapi***@***.cloud.databricks.com?http_path=***&catalog=main&schema=test")
176
+ squares = [(i, i * i) for i in range(100)]
177
+ df = pd.DataFrame(data=squares,columns=['x','x_squared'])
178
+
179
+ with engine.connect() as conn:
180
+ # This will write the contents of `df` to `main.test.squares`
181
+ df.to_sql('squares',conn)
182
+ ```
183
+
184
+ ## [`PrimaryKey()`](https://docs.sqlalchemy.org/en/13/core/constraints.html#sqlalchemy.schema.PrimaryKeyConstraint) and [`ForeignKey()`](https://docs.sqlalchemy.org/en/13/core/constraints.html#defining-foreign-keys)
185
+
186
+ Unity Catalog workspaces in Databricks support PRIMARY KEY and FOREIGN KEY constraints. _Note that Databricks Runtime does not enforce the integrity of FOREIGN KEY constraints_. You can establish a primary key by setting `primary_key=True` when defining a column.
187
+
188
+ When building `ForeignKey` or `ForeignKeyConstraint` objects, you must specify a `name` for the constraint.
189
+
190
+ If your model definition requires a self-referential FOREIGN KEY constraint, you must include `use_alter=True` when defining the relationship.
191
+
192
+ ```python
193
+ from sqlalchemy import Table, Column, ForeignKey, BigInteger, String
194
+
195
+ users = Table(
196
+ "users",
197
+ metadata_obj,
198
+ Column("id", BigInteger, primary_key=True),
199
+ Column("name", String(), nullable=False),
200
+ Column("email", String()),
201
+ Column("manager_id", ForeignKey("users.id", name="fk_users_manager_id_x_users_id", use_alter=True))
202
+ )
203
+ ```
204
+
@@ -0,0 +1,10 @@
1
+ CHANGELOG.md,sha256=JU6ETCTYFt7p3CJ6XtKbu-fBBgvyfNn6MQnRfnjG7oY,163
2
+ databricks/sqlalchemy/__init__.py,sha256=vZg5CR1laCr50IFcOkzmp9-ysH83iTg81ygQcsPFTk8,60
3
+ databricks/sqlalchemy/dialect/__init__.py,sha256=hPPl180-V_xexLWhtwknNnhHboOYd2wXHelvmtk0E7c,10745
4
+ databricks/sqlalchemy/dialect/base.py,sha256=FBibGU9FV_UGlIpF8wyARhV0ImahIqsPELqvrxm_8Rk,494
5
+ databricks/sqlalchemy/dialect/compiler.py,sha256=P__ihEonyOJYotsVpirjbHf-lYBqBLLK-cM5LZdOSUo,792
6
+ databricks_sqlalchemy-1.0.1.dist-info/LICENSE,sha256=WgVm2VpfZ3CsUfPndD2NeCrEIcFA4UB-YnnW4ejxcbE,11346
7
+ databricks_sqlalchemy-1.0.1.dist-info/METADATA,sha256=o9xFiC352kC85oSTx5-5hjYMjXscGRvY2sK7_bkzqAY,11074
8
+ databricks_sqlalchemy-1.0.1.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
9
+ databricks_sqlalchemy-1.0.1.dist-info/entry_points.txt,sha256=AAjpsvZbVcoMAcWLIesoAT5FNZhBEcIhxdKknVua3jw,74
10
+ databricks_sqlalchemy-1.0.1.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 1.6.1
2
+ Generator: poetry-core 1.9.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [sqlalchemy.dialects]
2
+ databricks=databricks.sqlalchemy:DatabricksDialect
3
+
databricks/__init__.py DELETED
@@ -1,7 +0,0 @@
1
- # See: https://packaging.python.org/guides/packaging-namespace-packages/#pkgutil-style-namespace-packages
2
- #
3
- # This file must only contain the following line, or other packages in the databricks.* namespace
4
- # may not be importable. The contents of this file must be byte-for-byte equivalent across all packages.
5
- # If they are not, parallel package installation may lead to clobbered and invalid files.
6
- # Also see https://github.com/databricks/databricks-sdk-py/issues/343.
7
- __path__ = __import__("pkgutil").extend_path(__path__, __name__)
@@ -1,19 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: databricks-sqlalchemy
3
- Version: 0.0.1b1
4
- Summary: SQLAlchemy dialect for Databricks
5
- License: Apache-2.0
6
- Author: Databricks
7
- Author-email: databricks-sql-connector-maintainers@databricks.com
8
- Requires-Python: >=3.8.0,<4.0.0
9
- Classifier: License :: OSI Approved :: Apache Software License
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.8
12
- Classifier: Programming Language :: Python :: 3.9
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.11
15
- Description-Content-Type: text/markdown
16
-
17
- # SQLAlchemy Dialect for Databricks
18
-
19
- To install the SQLAlchemy dialect for Databricks, see [here](https://github.com/databricks/databricks-sql-python/blob/main/src/databricks/sqlalchemy/README.sqlalchemy.md).
@@ -1,5 +0,0 @@
1
- databricks/__init__.py,sha256=CF2MJcZFwbpn9TwQER8qnCDhkPooBGQNVkX4v7g6p3g,537
2
- databricks/sqlalchemy/__init__.py,sha256=xu_eBGmUyF5lQM8CjPetRCrVaBv_J9ZT2SxeeaL4GW4,38
3
- databricks_sqlalchemy-0.0.1b1.dist-info/METADATA,sha256=sVbclBRnTLzJ2YrokJLJMspqAfu3GwN_OYB4SKhh3NY,810
4
- databricks_sqlalchemy-0.0.1b1.dist-info/WHEEL,sha256=Zb28QaM1gQi8f4VCBhsUklF61CTlNYfs9YAZn-TOGFk,88
5
- databricks_sqlalchemy-0.0.1b1.dist-info/RECORD,,