ob-snowflake 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,127 @@
1
+ """ob-snowflake — OrionBelt Semantic Layer driver for Snowflake (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_snowflake
9
+
10
+ conn = ob_snowflake.connect(
11
+ account="xy12345.eu-west-1",
12
+ user="me",
13
+ password="secret",
14
+ database="MYDB",
15
+ warehouse="COMPUTE_WH",
16
+ )
17
+ with conn.cursor() as cur:
18
+ cur.execute("select:\\n dimensions:\\n - Region\\n measures:\\n - Revenue")
19
+ print(cur.fetchall())
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any
25
+
26
+ import snowflake.connector
27
+
28
+ from ob_snowflake.connection import Connection
29
+ from ob_snowflake.exceptions import (
30
+ DataError,
31
+ DatabaseError,
32
+ Error,
33
+ IntegrityError,
34
+ InterfaceError,
35
+ InternalError,
36
+ NotSupportedError,
37
+ OperationalError,
38
+ ProgrammingError,
39
+ Warning,
40
+ )
41
+
42
+ # PEP 249 module-level constants
43
+ apilevel = "2.0"
44
+ threadsafety = 1 # threads may share the module but not connections
45
+ paramstyle = "pyformat" # snowflake-connector-python uses %(name)s and %s
46
+
47
+
48
+ def connect(
49
+ account: str,
50
+ *,
51
+ user: str | None = None,
52
+ password: str | None = None,
53
+ database: str | None = None,
54
+ schema: str | None = None,
55
+ warehouse: str | None = None,
56
+ role: str | None = None,
57
+ authenticator: str | None = None,
58
+ # OrionBelt parameters
59
+ ob_api_url: str = "http://localhost:8000",
60
+ ob_timeout: int = 30,
61
+ ) -> Connection:
62
+ """Open a Snowflake connection with OBML support.
63
+
64
+ Parameters
65
+ ----------
66
+ account : str
67
+ Snowflake account identifier (e.g. ``xy12345.eu-west-1``).
68
+ user : str, optional
69
+ Username.
70
+ password : str, optional
71
+ Password.
72
+ database : str, optional
73
+ Default database.
74
+ schema : str, optional
75
+ Default schema.
76
+ warehouse : str, optional
77
+ Virtual warehouse.
78
+ role : str, optional
79
+ Snowflake role.
80
+ authenticator : str, optional
81
+ Authentication method (e.g. ``"externalbrowser"`` for SSO).
82
+ ob_api_url : str
83
+ OrionBelt REST API URL (must be running in single-model mode).
84
+ ob_timeout : int
85
+ HTTP timeout in seconds for OBML compilation.
86
+ """
87
+ connect_kwargs: dict[str, Any] = {"account": account}
88
+ if user is not None:
89
+ connect_kwargs["user"] = user
90
+ if password is not None:
91
+ connect_kwargs["password"] = password
92
+ if database is not None:
93
+ connect_kwargs["database"] = database
94
+ if schema is not None:
95
+ connect_kwargs["schema"] = schema
96
+ if warehouse is not None:
97
+ connect_kwargs["warehouse"] = warehouse
98
+ if role is not None:
99
+ connect_kwargs["role"] = role
100
+ if authenticator is not None:
101
+ connect_kwargs["authenticator"] = authenticator
102
+
103
+ native = snowflake.connector.connect(**connect_kwargs)
104
+ return Connection(
105
+ native,
106
+ ob_api_url=ob_api_url,
107
+ ob_timeout=ob_timeout,
108
+ )
109
+
110
+
111
+ __all__ = [
112
+ "apilevel",
113
+ "threadsafety",
114
+ "paramstyle",
115
+ "connect",
116
+ "Connection",
117
+ "Warning",
118
+ "Error",
119
+ "InterfaceError",
120
+ "DatabaseError",
121
+ "DataError",
122
+ "OperationalError",
123
+ "IntegrityError",
124
+ "InternalError",
125
+ "ProgrammingError",
126
+ "NotSupportedError",
127
+ ]
@@ -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,64 @@
1
+ """PEP 249 Connection wrapping ``snowflake.connector.connection.SnowflakeConnection``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ob_snowflake.cursor import Cursor
8
+ from ob_snowflake.exceptions import ProgrammingError
9
+
10
+
11
+ class Connection:
12
+ """DB-API 2.0 connection that wraps a native Snowflake 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,
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
+ """Commit the current transaction."""
46
+ self._check_open()
47
+ self._native.commit()
48
+
49
+ def rollback(self) -> None:
50
+ """Rollback the current transaction."""
51
+ self._check_open()
52
+ self._native.rollback()
53
+
54
+ def close(self) -> None:
55
+ """Close the connection."""
56
+ if not self._closed:
57
+ self._native.close()
58
+ self._closed = True
59
+
60
+ def __enter__(self) -> Connection:
61
+ return self
62
+
63
+ def __exit__(self, *exc: object) -> None:
64
+ self.close()
ob_snowflake/cursor.py ADDED
@@ -0,0 +1,149 @@
1
+ """PEP 249 Cursor with OBML interception for Snowflake."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ob_snowflake.compiler import compile_obml, is_obml, parse_obml
8
+ from ob_snowflake.exceptions import NotSupportedError, ProgrammingError
9
+ from ob_snowflake.type_codes import SF_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 Snowflake 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,
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
+ native_desc = self._native.description
39
+ if native_desc is None:
40
+ return None
41
+ cols: list[tuple[str, Any, None, None, None, None, None]] = []
42
+ for col in native_desc:
43
+ name = col.name
44
+ type_id = col.type_code
45
+ type_code = SF_TYPE_MAP.get(type_id, STRING)
46
+ cols.append((name, type_code, None, None, None, None, None))
47
+ return tuple(cols)
48
+
49
+ @property
50
+ def rowcount(self) -> int:
51
+ return self._native.rowcount
52
+
53
+ def _check_open(self) -> None:
54
+ if self._closed:
55
+ raise ProgrammingError("Cursor is closed.")
56
+
57
+ def execute(self, operation: str, parameters: Any = None) -> Cursor:
58
+ """Execute a query — OBML YAML or plain SQL."""
59
+ self._check_open()
60
+ sql = self._resolve_sql(operation)
61
+ if parameters is not None:
62
+ self._native.execute(sql, parameters)
63
+ else:
64
+ self._native.execute(sql)
65
+ return self
66
+
67
+ def executemany(self, operation: str, seq_of_parameters: Any) -> None:
68
+ """Execute against all parameter sequences.
69
+
70
+ OBML queries are not supported with executemany — raises NotSupportedError.
71
+ """
72
+ self._check_open()
73
+ if is_obml(operation):
74
+ raise NotSupportedError("executemany() is not supported for OBML queries.")
75
+ for params in seq_of_parameters:
76
+ self._native.execute(operation, params)
77
+
78
+ def _resolve_sql(self, operation: str) -> str:
79
+ """Compile OBML to SQL or return plain SQL unchanged."""
80
+ if not is_obml(operation):
81
+ return operation
82
+ obml = parse_obml(operation)
83
+ return compile_obml(
84
+ obml,
85
+ dialect="snowflake",
86
+ ob_api_url=self._ob_api_url,
87
+ ob_timeout=self._ob_timeout,
88
+ )
89
+
90
+ def fetchone(self) -> tuple[Any, ...] | None:
91
+ """Fetch the next row."""
92
+ self._check_open()
93
+ row = self._native.fetchone()
94
+ return tuple(row) if row is not None else None
95
+
96
+ def fetchmany(self, size: int | None = None) -> list[tuple[Any, ...]]:
97
+ """Fetch the next *size* rows."""
98
+ self._check_open()
99
+ n = size if size is not None else self.arraysize
100
+ rows = self._native.fetchmany(n)
101
+ return [tuple(r) for r in rows]
102
+
103
+ def fetchall(self) -> list[tuple[Any, ...]]:
104
+ """Fetch all remaining rows."""
105
+ self._check_open()
106
+ rows = self._native.fetchall()
107
+ return [tuple(r) for r in rows]
108
+
109
+ def fetch_arrow_table(self) -> Any:
110
+ """Fetch all remaining rows as a PyArrow Table.
111
+
112
+ Snowflake connector returns Arrow natively (zero-copy from the
113
+ internal result format). Significantly more memory-efficient
114
+ than materialising Python row objects via ``fetchall()``.
115
+ """
116
+ self._check_open()
117
+ return self._native.fetch_arrow_all()
118
+
119
+ def close(self) -> None:
120
+ """Close the cursor."""
121
+ if not self._closed:
122
+ self._native.close()
123
+ self._closed = True
124
+
125
+ def setinputsizes(self, sizes: Any) -> None:
126
+ """No-op — required by PEP 249."""
127
+
128
+ def setoutputsize(self, size: int, column: int | None = None) -> None:
129
+ """No-op — required by PEP 249."""
130
+
131
+ @property
132
+ def lastrowid(self) -> None:
133
+ """Snowflake does not expose lastrowid via connector cursor."""
134
+ return None
135
+
136
+ def __enter__(self) -> Cursor:
137
+ return self
138
+
139
+ def __exit__(self, *exc: object) -> None:
140
+ self.close()
141
+
142
+ def __iter__(self) -> Cursor:
143
+ return self
144
+
145
+ def __next__(self) -> tuple[Any, ...]:
146
+ row = self.fetchone()
147
+ if row is None:
148
+ raise StopIteration
149
+ 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_snowflake.exceptions import ProgrammingError``
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from ob_driver_core.exceptions import (
9
+ DataError,
10
+ DatabaseError,
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,29 @@
1
+ """PEP 249 type objects — re-exported from ob-driver-core plus Snowflake type mapping.
2
+
3
+ snowflake-connector-python cursor.description returns integer type IDs as type_code.
4
+ The SF_TYPE_MAP maps Snowflake field type IDs 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", "SF_TYPE_MAP"]
12
+
13
+ # Snowflake type IDs from snowflake.connector.constants.FIELD_ID_TO_NAME
14
+ SF_TYPE_MAP: dict[int, object] = {
15
+ 0: NUMBER, # FIXED (NUMBER/INT/DECIMAL)
16
+ 1: NUMBER, # REAL (FLOAT)
17
+ 2: STRING, # TEXT (VARCHAR/STRING)
18
+ 3: DATETIME, # DATE
19
+ 4: DATETIME, # TIMESTAMP_NTZ
20
+ 5: STRING, # VARIANT
21
+ 6: DATETIME, # TIMESTAMP_LTZ
22
+ 7: DATETIME, # TIMESTAMP_TZ
23
+ 8: DATETIME, # TIMESTAMP (alias)
24
+ 9: STRING, # OBJECT
25
+ 10: STRING, # ARRAY
26
+ 11: BINARY, # BINARY
27
+ 12: DATETIME, # TIME
28
+ 13: STRING, # BOOLEAN
29
+ }
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: ob-snowflake
3
+ Version: 0.1.0
4
+ Summary: OrionBelt Semantic Layer driver for Snowflake (DB-API 2.0)
5
+ Author-email: Ralf Becher <info@orionbelt.ai>
6
+ License: BSL-1.1
7
+ License-File: LICENSE
8
+ Keywords: db-api,obml,orionbelt,semantic-layer,snowflake
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: ob-driver-core>=0.1
11
+ Requires-Dist: snowflake-connector-python>=3.0
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-snowflake
23
+
24
+ OrionBelt Semantic Layer driver for Snowflake (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-snowflake
32
+ ```
33
+
34
+ ## License
35
+
36
+ BSL-1.1 — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,11 @@
1
+ ob_snowflake/__init__.py,sha256=lCb1hwtBk9vGzFjkdbMRXFd_jensJGjKk6_QOvWvLIE,3333
2
+ ob_snowflake/compiler.py,sha256=WTYZzdsJJiOxgIDS3NpDOpk_SG7_0weT4el-xuuBGsE,264
3
+ ob_snowflake/connection.py,sha256=Ywa64ikP_kLpD3vkHoHRcsdl0IIT_GinAy85b-O3kLA,1752
4
+ ob_snowflake/cursor.py,sha256=Kddm9wSTYhrT2VdmQREiQ1HY1KJt0gW1BbeJ1g9MB-o,4819
5
+ ob_snowflake/exceptions.py,sha256=W3j7EReU7_WQTvsgj3AFKlDg_qn7A6Vq3Z7rvrhzJqY,639
6
+ ob_snowflake/type_codes.py,sha256=b3CKjv3nPbvlXNapC0apoFA1k0beiR1yzFe4o1dXBtg,1001
7
+ ob_snowflake-0.1.0.dist-info/METADATA,sha256=I1ND8CsFPZeNgtrrwgImIRlFrdpNdP7JwPlMdcmq_CA,1031
8
+ ob_snowflake-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
9
+ ob_snowflake-0.1.0.dist-info/entry_points.txt,sha256=Gsa_3yDu5LANV6IPHeEwVc5VyE16tj2xq7KUTe2oEiM,77
10
+ ob_snowflake-0.1.0.dist-info/licenses/LICENSE,sha256=t-vr73N5s2w6yxpCnwo5r_QuB5_u6FuEovAYMjlfe7E,3378
11
+ ob_snowflake-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.snowflake = ob_snowflake.dialect:OBSnowflakeDialect
@@ -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/.