ob-databricks 0.1.0__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,113 @@
1
+ """ob-databricks — OrionBelt Semantic Layer driver for Databricks (PEP 249 DB-API 2.0).
2
+
3
+ Requires the OrionBelt REST API running in single-model mode (MODEL_FILE set).
4
+ OBML queries are compiled to SQL via ``POST /v1/query/sql``.
5
+
6
+ Usage::
7
+
8
+ import ob_databricks
9
+
10
+ conn = ob_databricks.connect(
11
+ server_hostname="adb-xxx.azuredatabricks.net",
12
+ http_path="/sql/1.0/warehouses/abc123",
13
+ access_token="dapi...",
14
+ )
15
+ with conn.cursor() as cur:
16
+ cur.execute("select:\\n dimensions:\\n - Region\\n measures:\\n - Revenue")
17
+ print(cur.fetchall())
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Any
23
+
24
+ from databricks import sql
25
+
26
+ from ob_databricks.connection import Connection
27
+ from ob_databricks.exceptions import (
28
+ DatabaseError,
29
+ DataError,
30
+ Error,
31
+ IntegrityError,
32
+ InterfaceError,
33
+ InternalError,
34
+ NotSupportedError,
35
+ OperationalError,
36
+ ProgrammingError,
37
+ Warning,
38
+ )
39
+
40
+ # PEP 249 module-level constants
41
+ apilevel = "2.0"
42
+ threadsafety = 1 # threads may share the module but not connections
43
+ paramstyle = "pyformat" # databricks-sql-connector uses %(name)s
44
+
45
+
46
+ def connect(
47
+ server_hostname: str,
48
+ http_path: str,
49
+ *,
50
+ access_token: str | None = None,
51
+ catalog: str = "hive_metastore",
52
+ schema: str = "default",
53
+ # OrionBelt parameters
54
+ ob_api_url: str = "http://localhost:8000",
55
+ ob_timeout: int = 30,
56
+ **kwargs: Any, # noqa: ANN401
57
+ ) -> Connection:
58
+ """Open a Databricks connection with OBML support.
59
+
60
+ Parameters
61
+ ----------
62
+ server_hostname : str
63
+ Databricks workspace hostname (e.g. ``adb-xxx.azuredatabricks.net``).
64
+ http_path : str
65
+ SQL warehouse HTTP path (e.g. ``/sql/1.0/warehouses/abc123``).
66
+ access_token : str, optional
67
+ Personal access token or OAuth token.
68
+ catalog : str
69
+ Unity Catalog name (default: ``hive_metastore``).
70
+ schema : str
71
+ Schema name (default: ``default``).
72
+ ob_api_url : str
73
+ OrionBelt REST API URL (must be running in single-model mode).
74
+ ob_timeout : int
75
+ HTTP timeout in seconds for OBML compilation.
76
+ **kwargs
77
+ Extra keyword arguments forwarded to ``databricks.sql.connect()``.
78
+ """
79
+ connect_kwargs: dict[str, Any] = {
80
+ "server_hostname": server_hostname,
81
+ "http_path": http_path,
82
+ "catalog": catalog,
83
+ "schema": schema,
84
+ }
85
+ if access_token is not None:
86
+ connect_kwargs["access_token"] = access_token
87
+ connect_kwargs.update(kwargs)
88
+
89
+ native = sql.connect(**connect_kwargs)
90
+ return Connection(
91
+ native,
92
+ ob_api_url=ob_api_url,
93
+ ob_timeout=ob_timeout,
94
+ )
95
+
96
+
97
+ __all__ = [
98
+ "apilevel",
99
+ "threadsafety",
100
+ "paramstyle",
101
+ "connect",
102
+ "Connection",
103
+ "Warning",
104
+ "Error",
105
+ "InterfaceError",
106
+ "DatabaseError",
107
+ "DataError",
108
+ "OperationalError",
109
+ "IntegrityError",
110
+ "InternalError",
111
+ "ProgrammingError",
112
+ "NotSupportedError",
113
+ ]
@@ -0,0 +1,8 @@
1
+ """OrionBelt compilation bridge — delegates to ob-driver-core."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ob_driver_core.compiler import compile_obml
6
+ from ob_driver_core.detection import is_obml, parse_obml
7
+
8
+ __all__ = ["compile_obml", "is_obml", "parse_obml"]
@@ -0,0 +1,62 @@
1
+ """PEP 249 Connection wrapping ``databricks.sql`` connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ob_databricks.cursor import Cursor
8
+ from ob_databricks.exceptions import ProgrammingError
9
+
10
+
11
+ class Connection:
12
+ """DB-API 2.0 connection that wraps a native Databricks SQL connector connection.
13
+
14
+ OBML queries are compiled to SQL via the OrionBelt REST API
15
+ (single-model mode, ``/v1/query/sql`` shortcut).
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ native: Any, # noqa: ANN401
21
+ *,
22
+ ob_api_url: str = "http://localhost:8000",
23
+ ob_timeout: int = 30,
24
+ ) -> None:
25
+ self._native = native
26
+ self._closed = False
27
+ self._ob_api_url = ob_api_url
28
+ self._ob_timeout = ob_timeout
29
+
30
+ def _check_open(self) -> None:
31
+ if self._closed:
32
+ raise ProgrammingError("Connection is closed.")
33
+
34
+ def cursor(self) -> Cursor:
35
+ """Return a new Cursor for this connection."""
36
+ self._check_open()
37
+ native_cursor = self._native.cursor()
38
+ return Cursor(
39
+ native_cursor,
40
+ ob_api_url=self._ob_api_url,
41
+ ob_timeout=self._ob_timeout,
42
+ )
43
+
44
+ def commit(self) -> None:
45
+ """No-op — Databricks SQL warehouses auto-commit all statements."""
46
+ self._check_open()
47
+
48
+ def rollback(self) -> None:
49
+ """No-op — Databricks SQL warehouses do not support transactions."""
50
+ self._check_open()
51
+
52
+ def close(self) -> None:
53
+ """Close the connection."""
54
+ if not self._closed:
55
+ self._native.close()
56
+ self._closed = True
57
+
58
+ def __enter__(self) -> Connection:
59
+ return self
60
+
61
+ def __exit__(self, *exc: object) -> None:
62
+ self.close()
@@ -0,0 +1,153 @@
1
+ """PEP 249 Cursor with OBML interception for Databricks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ob_databricks.compiler import compile_obml, is_obml, parse_obml
8
+ from ob_databricks.exceptions import NotSupportedError, ProgrammingError
9
+ from ob_databricks.type_codes import DBR_TYPE_MAP, STRING
10
+
11
+
12
+ class Cursor:
13
+ """DB-API 2.0 cursor that intercepts OBML YAML queries.
14
+
15
+ If the query is OBML, it is compiled to Databricks SQL via the OrionBelt
16
+ REST API before execution. Plain SQL is passed through unchanged.
17
+ """
18
+
19
+ arraysize: int = 1
20
+
21
+ def __init__(
22
+ self,
23
+ native: Any, # noqa: ANN401
24
+ *,
25
+ ob_api_url: str = "http://localhost:8000",
26
+ ob_timeout: int = 30,
27
+ ) -> None:
28
+ self._native = native
29
+ self._closed = False
30
+ self._ob_api_url = ob_api_url
31
+ self._ob_timeout = ob_timeout
32
+
33
+ @property
34
+ def description(
35
+ self,
36
+ ) -> tuple[tuple[str, Any, None, None, None, None, None], ...] | None:
37
+ """PEP 249 cursor description — 7-item tuples per column.
38
+
39
+ Databricks SQL connector returns string type names in ``type_code``
40
+ (index 1 of each description column). These are mapped to PEP 249
41
+ type objects via :data:`DBR_TYPE_MAP`.
42
+ """
43
+ native_desc = self._native.description
44
+ if native_desc is None:
45
+ return None
46
+ cols: list[tuple[str, Any, None, None, None, None, None]] = []
47
+ for col in native_desc:
48
+ name = col[0]
49
+ type_name = str(col[1]).lower() if col[1] is not None else ""
50
+ type_code = DBR_TYPE_MAP.get(type_name, STRING)
51
+ cols.append((name, type_code, None, None, None, None, None))
52
+ return tuple(cols)
53
+
54
+ @property
55
+ def rowcount(self) -> int:
56
+ return self._native.rowcount
57
+
58
+ def _check_open(self) -> None:
59
+ if self._closed:
60
+ raise ProgrammingError("Cursor is closed.")
61
+
62
+ def execute(self, operation: str, parameters: Any = None) -> Cursor: # noqa: ANN401
63
+ """Execute a query — OBML YAML or plain SQL."""
64
+ self._check_open()
65
+ sql = self._resolve_sql(operation)
66
+ if parameters is not None:
67
+ self._native.execute(sql, parameters)
68
+ else:
69
+ self._native.execute(sql)
70
+ return self
71
+
72
+ def executemany(self, operation: str, seq_of_parameters: Any) -> None: # noqa: ANN401
73
+ """Execute against all parameter sequences.
74
+
75
+ OBML queries are not supported with executemany — raises NotSupportedError.
76
+ """
77
+ self._check_open()
78
+ if is_obml(operation):
79
+ raise NotSupportedError("executemany() is not supported for OBML queries.")
80
+ for params in seq_of_parameters:
81
+ self._native.execute(operation, params)
82
+
83
+ def _resolve_sql(self, operation: str) -> str:
84
+ """Compile OBML to SQL or return plain SQL unchanged."""
85
+ if not is_obml(operation):
86
+ return operation
87
+ obml = parse_obml(operation)
88
+ return compile_obml(
89
+ obml,
90
+ dialect="databricks",
91
+ ob_api_url=self._ob_api_url,
92
+ ob_timeout=self._ob_timeout,
93
+ )
94
+
95
+ def fetchone(self) -> tuple[Any, ...] | None:
96
+ """Fetch the next row."""
97
+ self._check_open()
98
+ row = self._native.fetchone()
99
+ return tuple(row) if row is not None else None
100
+
101
+ def fetchmany(self, size: int | None = None) -> list[tuple[Any, ...]]:
102
+ """Fetch the next *size* rows."""
103
+ self._check_open()
104
+ n = size if size is not None else self.arraysize
105
+ rows = self._native.fetchmany(n)
106
+ return [tuple(r) for r in rows]
107
+
108
+ def fetchall(self) -> list[tuple[Any, ...]]:
109
+ """Fetch all remaining rows."""
110
+ self._check_open()
111
+ rows = self._native.fetchall()
112
+ return [tuple(r) for r in rows]
113
+
114
+ def fetch_arrow_table(self) -> Any: # noqa: ANN401
115
+ """Fetch all remaining rows as a PyArrow Table.
116
+
117
+ Databricks SQL connector returns Arrow natively via its internal
118
+ Thrift/Arrow result format. More memory-efficient than ``fetchall()``.
119
+ """
120
+ self._check_open()
121
+ return self._native.fetchall_arrow()
122
+
123
+ def close(self) -> None:
124
+ """Close the cursor."""
125
+ if not self._closed:
126
+ self._native.close()
127
+ self._closed = True
128
+
129
+ def setinputsizes(self, sizes: Any) -> None: # noqa: ANN401
130
+ """No-op — required by PEP 249."""
131
+
132
+ def setoutputsize(self, size: int, column: int | None = None) -> None:
133
+ """No-op — required by PEP 249."""
134
+
135
+ @property
136
+ def lastrowid(self) -> None:
137
+ """Databricks does not expose lastrowid via connector cursor."""
138
+ return None
139
+
140
+ def __enter__(self) -> Cursor:
141
+ return self
142
+
143
+ def __exit__(self, *exc: object) -> None:
144
+ self.close()
145
+
146
+ def __iter__(self) -> Cursor:
147
+ return self
148
+
149
+ def __next__(self) -> tuple[Any, ...]:
150
+ row = self.fetchone()
151
+ if row is None:
152
+ raise StopIteration
153
+ return row
@@ -0,0 +1,32 @@
1
+ """PEP 249 exceptions — re-exported from ob-driver-core for convenience.
2
+
3
+ Allows users to do: ``from ob_databricks.exceptions import ProgrammingError``
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from ob_driver_core.exceptions import (
9
+ DatabaseError,
10
+ DataError,
11
+ Error,
12
+ IntegrityError,
13
+ InterfaceError,
14
+ InternalError,
15
+ NotSupportedError,
16
+ OperationalError,
17
+ ProgrammingError,
18
+ Warning,
19
+ )
20
+
21
+ __all__ = [
22
+ "Warning",
23
+ "Error",
24
+ "InterfaceError",
25
+ "DatabaseError",
26
+ "DataError",
27
+ "OperationalError",
28
+ "IntegrityError",
29
+ "InternalError",
30
+ "ProgrammingError",
31
+ "NotSupportedError",
32
+ ]
@@ -0,0 +1,42 @@
1
+ """PEP 249 type objects — re-exported from ob-driver-core plus Databricks type mapping.
2
+
3
+ databricks-sql-connector cursor.description returns string type names as type_code.
4
+ The DBR_TYPE_MAP maps Databricks type names to PEP 249 type objects.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from ob_driver_core.type_codes import BINARY, DATETIME, NUMBER, ROWID, STRING
10
+
11
+ __all__ = ["STRING", "BINARY", "NUMBER", "DATETIME", "ROWID", "DBR_TYPE_MAP"]
12
+
13
+ # Databricks SQL connector type names from cursor.description
14
+ # https://docs.databricks.com/en/sql/language-manual/sql-ref-datatypes.html
15
+ DBR_TYPE_MAP: dict[str, object] = {
16
+ # Numeric
17
+ "boolean": STRING,
18
+ "byte": NUMBER,
19
+ "tinyint": NUMBER,
20
+ "short": NUMBER,
21
+ "smallint": NUMBER,
22
+ "int": NUMBER,
23
+ "integer": NUMBER,
24
+ "long": NUMBER,
25
+ "bigint": NUMBER,
26
+ "float": NUMBER,
27
+ "double": NUMBER,
28
+ "decimal": NUMBER,
29
+ # String
30
+ "string": STRING,
31
+ "char": STRING,
32
+ "varchar": STRING,
33
+ # Date/Time
34
+ "date": DATETIME,
35
+ "timestamp": DATETIME,
36
+ # Binary
37
+ "binary": BINARY,
38
+ # Complex (serialize as string)
39
+ "array": STRING,
40
+ "map": STRING,
41
+ "struct": STRING,
42
+ }
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: ob-databricks
3
+ Version: 0.1.0
4
+ Summary: OrionBelt Semantic Layer driver for Databricks (DB-API 2.0)
5
+ Author-email: Ralf Becher <info@orionbelt.ai>
6
+ License: BSL-1.1
7
+ License-File: LICENSE
8
+ Keywords: databricks,db-api,obml,orionbelt,semantic-layer
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: databricks-sql-connector>=3.0
11
+ Requires-Dist: ob-driver-core>=0.1
12
+ Provides-Extra: dev
13
+ Requires-Dist: mypy>=1.10; extra == 'dev'
14
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
15
+ Requires-Dist: pytest>=8.0; extra == 'dev'
16
+ Requires-Dist: respx>=0.21; extra == 'dev'
17
+ Requires-Dist: ruff>=0.4; extra == 'dev'
18
+ Provides-Extra: sqlalchemy
19
+ Requires-Dist: sqlalchemy>=2.0; extra == 'sqlalchemy'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # ob-databricks
23
+
24
+ OrionBelt Semantic Layer driver for Databricks (DB-API 2.0)
25
+
26
+ Part of the [OrionBelt Semantic Layer](https://github.com/ralfbecher/orionbelt-semantic-layer) project.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install ob-databricks
32
+ ```
33
+
34
+ ## License
35
+
36
+ BSL-1.1 — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,11 @@
1
+ ob_databricks/__init__.py,sha256=JtbEL0v5bxVHQuA_fFjeqHQz0XhQ17E3ABO4RpQ4R9M,2984
2
+ ob_databricks/compiler.py,sha256=WTYZzdsJJiOxgIDS3NpDOpk_SG7_0weT4el-xuuBGsE,264
3
+ ob_databricks/connection.py,sha256=fBUo4yAX6CsEMh5EeobBcgJNpTeL9g_LfskPYxpgnW4,1751
4
+ ob_databricks/cursor.py,sha256=D30HXLMhvTBGqMbTW0KJB-w9Me-9ywHREAnMrcjkvA4,5098
5
+ ob_databricks/exceptions.py,sha256=Au4Er33l-WMXtE9E6BNY--WpBVaA11I3ihHHJio3O4k,640
6
+ ob_databricks/type_codes.py,sha256=Xuud_thjXQ196vEwuQVZUkq2gvuRQF9R0c0bPozCyK8,1170
7
+ ob_databricks-0.1.0.dist-info/METADATA,sha256=YUAkWmwkQqUI4-YfBnKQ7G9v3YYnzUMvtR6xvWQGgnA,1035
8
+ ob_databricks-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
9
+ ob_databricks-0.1.0.dist-info/entry_points.txt,sha256=1MsGJENBwxFm-bR-EAkNfLkUqEugnaS0-83AGxqc4AI,80
10
+ ob_databricks-0.1.0.dist-info/licenses/LICENSE,sha256=t-vr73N5s2w6yxpCnwo5r_QuB5_u6FuEovAYMjlfe7E,3378
11
+ ob_databricks-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [sqlalchemy.dialects]
2
+ ob.databricks = ob_databricks.dialect:OBDatabricksDialect
@@ -0,0 +1,70 @@
1
+ Business Source License 1.1
2
+
3
+ Parameters
4
+
5
+ Licensor: RALFORION d.o.o.
6
+ Licensed Work: OrionBelt Semantic Layer 1.0
7
+ The Licensed Work is (c) 2025 RALFORION d.o.o.
8
+ Additional Use Grant: You may use the Licensed Work for any purpose,
9
+ including production use, PROVIDED THAT you may
10
+ not embed OrionBelt in a commercial product or
11
+ provide it as part of a commercial service
12
+ without purchasing a commercial license from
13
+ the Licensor. Contact licensing@ralforion.com
14
+ for commercial licensing inquiries.
15
+ Change Date: 2030-03-16
16
+ Change License: Apache License, Version 2.0
17
+
18
+ -----------------------------------------------------------------------------
19
+
20
+ Business Source License 1.1
21
+
22
+ License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
23
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
24
+
25
+ Terms
26
+
27
+ The Licensor hereby grants you the right to copy, modify, create derivative
28
+ works, redistribute, and make non-production use of the Licensed Work. The
29
+ Licensor may make an Additional Use Grant, above, permitting limited
30
+ production use.
31
+
32
+ Effective on the Change Date, or the fourth anniversary of the first publicly
33
+ available distribution of a specific version of the Licensed Work under this
34
+ License, whichever comes first, the Licensor hereby grants you rights under
35
+ the terms of the Change License, and the rights granted in the paragraph
36
+ above terminate.
37
+
38
+ If your use of the Licensed Work does not comply with the requirements
39
+ currently in effect as described in this License, you must purchase a
40
+ commercial license from the Licensor, its affiliated entities, or authorized
41
+ resellers, or you must refrain from using the Licensed Work.
42
+
43
+ All copies of the original and modified Licensed Work, and derivative works
44
+ of the Licensed Work, are subject to this License. This License applies
45
+ separately for each version of the Licensed Work and the Change Date may vary
46
+ for each version of the Licensed Work released by Licensor.
47
+
48
+ You must conspicuously display this License on each original or modified copy
49
+ of the Licensed Work. If you receive the Licensed Work in original or
50
+ modified form from a third party, the terms and conditions set forth in this
51
+ License apply to your use of that work.
52
+
53
+ Any use of the Licensed Work in violation of this License will automatically
54
+ terminate your rights under this License for the current and all other
55
+ versions of the Licensed Work.
56
+
57
+ This License does not grant you any right in any trademark or logo of
58
+ Licensor or its affiliates (provided that you may use a trademark or logo of
59
+ Licensor as expressly required by this License).
60
+
61
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
62
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
63
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
64
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
65
+ TITLE.
66
+
67
+ MariaDB hereby grants you permission to use this License's text to license
68
+ your works, and to refer to it using the trademark "Business Source License",
69
+ as long as you comply with the Covenants of Licensor of MariaDB's Business Source
70
+ License Trademark Policy available at https://mariadb.com/bsl11/.