sql-glider 0.1.8__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.
@@ -0,0 +1,34 @@
1
+ sqlglider/__init__.py,sha256=gDf7s52dMcX7JuCZ1SLawcB1vb3U0yJCohu9RQAATBY,125
2
+ sqlglider/_version.py,sha256=Zaz3s9gl_rzsS46-ymJOALojMxviW77EJq_agE8knLk,704
3
+ sqlglider/cli.py,sha256=9sweHRVLk2iBSzCzT2Gcj8y1g1XKzq26iApQsMaFbx4,51786
4
+ sqlglider/global_models.py,sha256=2vyJXAuXOsXQpE-D3F0ejj7eR9z0nDWFjTkielhzM8k,356
5
+ sqlglider/catalog/__init__.py,sha256=2PqFPyzFXJ14FpSUcBmVK2L-a_ypWQHAbHFHxLDk_LE,814
6
+ sqlglider/catalog/base.py,sha256=R7htHC43InpH4uRjYk33dMYYji6oylHns7Ye_mgfjJE,3116
7
+ sqlglider/catalog/databricks.py,sha256=Ho1crIKv1bw-fXkWUhQhcKfiYQEGinGSxBS2zoVLB3o,9504
8
+ sqlglider/catalog/registry.py,sha256=KD1XrvK46xSrK5IikzbdbTSk_-wwRTXvyBxXn3m-Rx0,3391
9
+ sqlglider/dissection/__init__.py,sha256=ObXM7AXTJZvheIg36ps9KuFsXPV7WmWamaA4xPfxP4s,396
10
+ sqlglider/dissection/analyzer.py,sha256=-GD3-lTbfBthq1BW6HiDjvJx2y4LDmnUVHIVIb0HqrU,27085
11
+ sqlglider/dissection/formatters.py,sha256=M7gsmTNljRIeLIRv4D0vHvqJVrTqWSpsg7vem83zSzY,7302
12
+ sqlglider/dissection/models.py,sha256=RRD3RIteqbUBY6e-74skKDvMH3qeAUaqA2sFcrjP5GQ,3618
13
+ sqlglider/graph/__init__.py,sha256=4DDdrPM75CmeQWt7wHdBsjCm1s70BHGLYdijIbaUEKY,871
14
+ sqlglider/graph/builder.py,sha256=0ASA749b_FkcKMEVWiijAJP1QKt54ICY7VXxUuo3-y0,11953
15
+ sqlglider/graph/merge.py,sha256=uUZlm4BN3S9gRL66Cc2mzhbtuh4SVAv2n4cN4eUEQBU,4077
16
+ sqlglider/graph/models.py,sha256=EYmjv_WzDSNp_WfhJ6H-qBIOkAcoNKS7GRUryfKrHuY,9330
17
+ sqlglider/graph/query.py,sha256=LHU8Cvn7ZPPSEnqdDn2pF8f1_LQjIvNIrZqs8cFlb6U,9433
18
+ sqlglider/graph/serialization.py,sha256=vMXn7s35jA499e7l90vNVaJE_3QR_VHf3rEfQ9ZlgTQ,2781
19
+ sqlglider/lineage/__init__.py,sha256=llXMeI5_PIZaiBo8tKk3-wOubF4m_6QBHbn1FtWxT7k,256
20
+ sqlglider/lineage/analyzer.py,sha256=Vfh0g9xVEEUkQ87KZlCcZVPltDJ6Uos67PBtDyQ_i8U,64679
21
+ sqlglider/lineage/formatters.py,sha256=_Y9wcTX4JXn1vVnZ1xI656g1FF2rMjcAVc-GHjbd9QA,10389
22
+ sqlglider/templating/__init__.py,sha256=g3_wb6rSDI0usq2UUMDpn-J5kVwlAw3NtLdwbxL6UHs,1435
23
+ sqlglider/templating/base.py,sha256=y5bWAW7qXl_4pPyo5KycfHwNVvt1-7slZ63DAsvTE1s,2902
24
+ sqlglider/templating/jinja.py,sha256=o01UG72N4G1-tOT5LKK1Wkccv4nJH2VN4VFaMi5c1-g,5220
25
+ sqlglider/templating/registry.py,sha256=BJU3N2qNVMTUtkgbibyqo8Wme_acXQRw5XI-6ZVgyac,3476
26
+ sqlglider/templating/variables.py,sha256=5593PtLBcOxsnMCSRm2pGAD5I0Y9f__VV3_J_HfXVlQ,8010
27
+ sqlglider/utils/__init__.py,sha256=KGp9-UzKz_OFBOTFoSy-g-NXDZsvyWXG_9-1zcC6ePE,276
28
+ sqlglider/utils/config.py,sha256=iNJgSXFw3pmL2MCdvW3SJp4X2T3AQP2QyQuXIXT-6H0,4761
29
+ sqlglider/utils/file_utils.py,sha256=5_ff28E0r1R7emZzsOnRuHd-7zIX6873eyr1SuPEr4E,1093
30
+ sql_glider-0.1.8.dist-info/METADATA,sha256=ZXlzMjglSWRsOtaW8GIxJa62UKreUHR270WCRpGih-Q,28445
31
+ sql_glider-0.1.8.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
32
+ sql_glider-0.1.8.dist-info/entry_points.txt,sha256=HDuakHqHS5C0HFKsMIxMYmDU7-BLBGrnIJcYaVRu-s0,251
33
+ sql_glider-0.1.8.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
34
+ sql_glider-0.1.8.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,9 @@
1
+ [console_scripts]
2
+ sqlglider = sqlglider.cli:app
3
+
4
+ [sqlglider.catalogs]
5
+ databricks = sqlglider.catalog.databricks:DatabricksCatalog
6
+
7
+ [sqlglider.templaters]
8
+ jinja = sqlglider.templating.jinja:JinjaTemplater
9
+ none = sqlglider.templating.base:NoOpTemplater
@@ -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 [yyyy] [name of copyright owner]
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.
sqlglider/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """SQL Glider - SQL Utility Toolkit for better understanding, use, and governance of your queries."""
2
+
3
+ __version__ = "0.1.0"
sqlglider/_version.py ADDED
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.1.8'
32
+ __version_tuple__ = version_tuple = (0, 1, 8)
33
+
34
+ __commit_id__ = commit_id = None
@@ -0,0 +1,30 @@
1
+ """Catalog module for fetching DDL from remote data catalogs.
2
+
3
+ This module provides a plugin system for connecting to various data catalogs
4
+ (e.g., Databricks Unity Catalog) and fetching table DDL definitions.
5
+
6
+ Example:
7
+ >>> from sqlglider.catalog import get_catalog, list_catalogs
8
+ >>> print(list_catalogs())
9
+ ['databricks']
10
+ >>> catalog = get_catalog("databricks")
11
+ >>> catalog.configure({"warehouse_id": "abc123"})
12
+ >>> ddl = catalog.get_ddl("my_catalog.my_schema.my_table")
13
+ """
14
+
15
+ from sqlglider.catalog.base import Catalog, CatalogError
16
+ from sqlglider.catalog.registry import (
17
+ clear_registry,
18
+ get_catalog,
19
+ list_catalogs,
20
+ register_catalog,
21
+ )
22
+
23
+ __all__ = [
24
+ "Catalog",
25
+ "CatalogError",
26
+ "get_catalog",
27
+ "list_catalogs",
28
+ "register_catalog",
29
+ "clear_registry",
30
+ ]
@@ -0,0 +1,99 @@
1
+ """Base classes for catalog system.
2
+
3
+ This module defines the abstract interface for catalog providers and provides
4
+ the exception class for catalog-related errors.
5
+ """
6
+
7
+ from abc import ABC, abstractmethod
8
+ from typing import Any, Dict, List, Optional
9
+
10
+
11
+ class CatalogError(Exception):
12
+ """Exception raised when catalog operations fail."""
13
+
14
+ pass
15
+
16
+
17
+ class Catalog(ABC):
18
+ """Abstract base class for catalog providers.
19
+
20
+ All catalog implementations must inherit from this class and implement
21
+ the required methods. Catalogs are discovered via entry points and
22
+ can be used to fetch DDL definitions from remote data catalogs.
23
+
24
+ Example:
25
+ >>> class MyCatalog(Catalog):
26
+ ... @property
27
+ ... def name(self) -> str:
28
+ ... return "my-catalog"
29
+ ...
30
+ ... def get_ddl(self, table_name: str) -> str:
31
+ ... # Fetch DDL from remote catalog
32
+ ... return "CREATE TABLE ..."
33
+ ...
34
+ ... def get_ddl_batch(self, table_names: List[str]) -> Dict[str, str]:
35
+ ... return {name: self.get_ddl(name) for name in table_names}
36
+ """
37
+
38
+ @property
39
+ @abstractmethod
40
+ def name(self) -> str:
41
+ """Return the catalog provider name.
42
+
43
+ This name is used to identify the catalog in configuration
44
+ and CLI options.
45
+
46
+ Returns:
47
+ The unique name of this catalog provider.
48
+ """
49
+ pass
50
+
51
+ @abstractmethod
52
+ def get_ddl(self, table_name: str) -> str:
53
+ """Fetch DDL for a single table from the remote catalog.
54
+
55
+ Args:
56
+ table_name: The fully qualified table name (e.g., "catalog.schema.table").
57
+
58
+ Returns:
59
+ The DDL statement for creating the table.
60
+
61
+ Raises:
62
+ CatalogError: If the DDL cannot be fetched (table not found,
63
+ authentication failure, network error, etc.).
64
+ """
65
+ pass
66
+
67
+ @abstractmethod
68
+ def get_ddl_batch(self, table_names: List[str]) -> Dict[str, str]:
69
+ """Fetch DDL for multiple tables from the remote catalog.
70
+
71
+ This method may be more efficient than calling get_ddl() multiple
72
+ times, as implementations can batch requests where supported.
73
+
74
+ Args:
75
+ table_names: List of fully qualified table names.
76
+
77
+ Returns:
78
+ Dictionary mapping table names to their DDL statements.
79
+ Tables that couldn't be found will have None as their value.
80
+
81
+ Raises:
82
+ CatalogError: If the batch operation fails entirely.
83
+ """
84
+ pass
85
+
86
+ def configure(self, config: Optional[Dict[str, Any]] = None) -> None:
87
+ """Configure the catalog with provider-specific settings.
88
+
89
+ This method is called after instantiation to pass configuration
90
+ from sqlglider.toml or environment variables.
91
+
92
+ Args:
93
+ config: Provider-specific configuration dictionary.
94
+ Keys and values depend on the catalog implementation.
95
+
96
+ Raises:
97
+ CatalogError: If required configuration is missing or invalid.
98
+ """
99
+ pass
@@ -0,0 +1,255 @@
1
+ """Databricks catalog implementation.
2
+
3
+ This module provides integration with Databricks Unity Catalog for fetching
4
+ table DDL definitions using the Databricks SDK.
5
+
6
+ Requires the optional 'databricks' dependency:
7
+ pip install sql-glider[databricks]
8
+ """
9
+
10
+ import os
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from sqlglider.catalog.base import Catalog, CatalogError
14
+
15
+ # Lazy import to avoid requiring databricks-sdk unless actually used
16
+ _databricks_sdk_available: Optional[bool] = None
17
+
18
+
19
+ def _check_databricks_sdk() -> None:
20
+ """Check if databricks-sdk is installed."""
21
+ global _databricks_sdk_available
22
+ if _databricks_sdk_available is None:
23
+ try:
24
+ import databricks.sdk # noqa: F401
25
+
26
+ _databricks_sdk_available = True
27
+ except ImportError:
28
+ _databricks_sdk_available = False
29
+
30
+ if not _databricks_sdk_available:
31
+ raise CatalogError(
32
+ "The 'databricks-sdk' package is required for Databricks catalog support. "
33
+ "Install it with: pip install sql-glider[databricks]"
34
+ )
35
+
36
+
37
+ class DatabricksCatalog(Catalog):
38
+ """Databricks Unity Catalog provider.
39
+
40
+ Fetches table DDL using the Databricks SDK's statement execution API.
41
+
42
+ Authentication:
43
+ Authentication is handled by the Databricks SDK's unified authentication,
44
+ which automatically tries multiple methods in order:
45
+
46
+ 1. Direct configuration (host + token in sqlglider.toml)
47
+ 2. Environment variables (DATABRICKS_HOST, DATABRICKS_TOKEN, etc.)
48
+ 3. Databricks CLI profile (~/.databrickscfg) - use 'profile' config option
49
+ 4. Azure CLI authentication (for Azure Databricks)
50
+ 5. Google Cloud authentication (for GCP Databricks)
51
+ 6. OAuth M2M (client credentials) via environment variables:
52
+ - DATABRICKS_CLIENT_ID
53
+ - DATABRICKS_CLIENT_SECRET
54
+
55
+ For OAuth M2M, set these environment variables:
56
+ export DATABRICKS_HOST=https://your-workspace.cloud.databricks.com
57
+ export DATABRICKS_CLIENT_ID=your-client-id
58
+ export DATABRICKS_CLIENT_SECRET=your-client-secret
59
+
60
+ For Databricks CLI profile, either:
61
+ - Configure DEFAULT profile in ~/.databrickscfg
62
+ - Set profile name in sqlglider.toml: profile = "my-profile"
63
+
64
+ Configuration:
65
+ - warehouse_id (required): SQL warehouse ID for statement execution
66
+ - profile (optional): Databricks CLI profile name from ~/.databrickscfg
67
+ - host (optional): Databricks workspace URL
68
+ - token (optional): Personal access token (legacy, prefer OAuth)
69
+
70
+ Example:
71
+ >>> # Using environment variables or CLI profile (recommended)
72
+ >>> catalog = DatabricksCatalog()
73
+ >>> catalog.configure({"warehouse_id": "abc123def456"})
74
+ >>> ddl = catalog.get_ddl("my_catalog.my_schema.my_table")
75
+
76
+ >>> # Using specific CLI profile
77
+ >>> catalog.configure({"warehouse_id": "abc123", "profile": "dev-workspace"})
78
+ """
79
+
80
+ def __init__(self) -> None:
81
+ """Initialize the Databricks catalog."""
82
+ self._warehouse_id: Optional[str] = None
83
+ self._profile: Optional[str] = None
84
+ self._host: Optional[str] = None
85
+ self._token: Optional[str] = None
86
+ self._client: Any = None
87
+
88
+ @property
89
+ def name(self) -> str:
90
+ """Return the catalog provider name."""
91
+ return "databricks"
92
+
93
+ def configure(self, config: Optional[Dict[str, Any]] = None) -> None:
94
+ """Configure the Databricks catalog.
95
+
96
+ Args:
97
+ config: Configuration dictionary with optional keys:
98
+ - warehouse_id: SQL warehouse ID (required, or set DATABRICKS_WAREHOUSE_ID)
99
+ - profile: Databricks CLI profile name from ~/.databrickscfg
100
+ - host: Databricks workspace URL (only needed if not using profile/env)
101
+ - token: Personal access token (legacy, prefer OAuth or profile)
102
+
103
+ Raises:
104
+ CatalogError: If warehouse_id is not provided and not in environment.
105
+ """
106
+ config = config or {}
107
+
108
+ # Get warehouse_id from config or environment
109
+ self._warehouse_id = config.get("warehouse_id") or os.environ.get(
110
+ "DATABRICKS_WAREHOUSE_ID"
111
+ )
112
+ if not self._warehouse_id:
113
+ raise CatalogError(
114
+ "Databricks warehouse_id is required. "
115
+ "Set it in sqlglider.toml under [sqlglider.catalog.databricks] "
116
+ "or via the DATABRICKS_WAREHOUSE_ID environment variable."
117
+ )
118
+
119
+ # Get optional profile for CLI profile-based auth
120
+ self._profile = config.get("profile")
121
+
122
+ # Get optional host and token - only from config, not env vars
123
+ # Let the SDK handle env var discovery for better unified auth support
124
+ self._host = config.get("host")
125
+ self._token = config.get("token")
126
+
127
+ # Reset client so it gets recreated with new config
128
+ self._client = None
129
+
130
+ def _get_client(self) -> Any:
131
+ """Get or create the Databricks WorkspaceClient.
132
+
133
+ The SDK uses unified authentication, trying methods in this order:
134
+ 1. Explicit host/token if provided in config
135
+ 2. Profile from ~/.databrickscfg if specified
136
+ 3. Environment variables (DATABRICKS_HOST, DATABRICKS_TOKEN, etc.)
137
+ 4. OAuth M2M via DATABRICKS_CLIENT_ID/DATABRICKS_CLIENT_SECRET
138
+ 5. Azure CLI / Google Cloud auth for cloud-hosted workspaces
139
+
140
+ Returns:
141
+ The WorkspaceClient instance.
142
+
143
+ Raises:
144
+ CatalogError: If the SDK is not installed or authentication fails.
145
+ """
146
+ _check_databricks_sdk()
147
+
148
+ if self._client is None:
149
+ from databricks.sdk import WorkspaceClient
150
+
151
+ # Build kwargs for WorkspaceClient
152
+ # Only pass values that are explicitly configured
153
+ # Let SDK handle env var discovery for unified auth
154
+ kwargs: Dict[str, Any] = {}
155
+ if self._profile:
156
+ kwargs["profile"] = self._profile
157
+ if self._host:
158
+ kwargs["host"] = self._host
159
+ if self._token:
160
+ kwargs["token"] = self._token
161
+
162
+ try:
163
+ self._client = WorkspaceClient(**kwargs)
164
+ except Exception as e:
165
+ raise CatalogError(
166
+ f"Failed to authenticate with Databricks: {e}"
167
+ ) from e
168
+
169
+ return self._client
170
+
171
+ def get_ddl(self, table_name: str) -> str:
172
+ """Fetch DDL for a single table from Databricks.
173
+
174
+ Uses SHOW CREATE TABLE to get the full DDL statement.
175
+
176
+ Args:
177
+ table_name: The fully qualified table name (catalog.schema.table).
178
+
179
+ Returns:
180
+ The CREATE TABLE DDL statement.
181
+
182
+ Raises:
183
+ CatalogError: If the table is not found or the query fails.
184
+ """
185
+ if not self._warehouse_id:
186
+ raise CatalogError(
187
+ "Catalog not configured. Call configure() with warehouse_id first."
188
+ )
189
+
190
+ client = self._get_client()
191
+
192
+ try:
193
+ # Execute SHOW CREATE TABLE statement
194
+ response = client.statement_execution.execute_statement(
195
+ warehouse_id=self._warehouse_id,
196
+ statement=f"SHOW CREATE TABLE {table_name}",
197
+ wait_timeout="30s",
198
+ )
199
+
200
+ # Check for errors
201
+ if response.status and response.status.state:
202
+ state = response.status.state.value
203
+ if state == "FAILED":
204
+ error_msg = (
205
+ response.status.error.message
206
+ if response.status.error
207
+ else "Unknown error"
208
+ )
209
+ raise CatalogError(
210
+ f"Failed to get DDL for '{table_name}': {error_msg}"
211
+ )
212
+
213
+ # Extract DDL from result
214
+ if response.result and response.result.data_array:
215
+ # SHOW CREATE TABLE returns a single row with the DDL
216
+ ddl_parts = []
217
+ for row in response.result.data_array:
218
+ if row:
219
+ ddl_parts.append(str(row[0]))
220
+ return "\n".join(ddl_parts)
221
+
222
+ raise CatalogError(f"No DDL returned for table '{table_name}'")
223
+
224
+ except CatalogError:
225
+ raise
226
+ except Exception as e:
227
+ raise CatalogError(f"Failed to fetch DDL for '{table_name}': {e}") from e
228
+
229
+ def get_ddl_batch(self, table_names: List[str]) -> Dict[str, str]:
230
+ """Fetch DDL for multiple tables from Databricks.
231
+
232
+ Currently executes individual queries for each table.
233
+ Future optimization could use parallel execution.
234
+
235
+ Args:
236
+ table_names: List of fully qualified table names.
237
+
238
+ Returns:
239
+ Dictionary mapping table names to their DDL statements.
240
+ Tables that couldn't be found will have error messages as values
241
+ prefixed with "ERROR: ".
242
+
243
+ Raises:
244
+ CatalogError: If the batch operation fails entirely.
245
+ """
246
+ results: Dict[str, str] = {}
247
+
248
+ for table_name in table_names:
249
+ try:
250
+ results[table_name] = self.get_ddl(table_name)
251
+ except CatalogError as e:
252
+ # Store error message for this table but continue with others
253
+ results[table_name] = f"ERROR: {e}"
254
+
255
+ return results