ob-snowflake 0.1.0__tar.gz

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,35 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.so
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ *.egg
9
+ .eggs/
10
+ .venv/
11
+ venv/
12
+ .env
13
+ *.db
14
+ *.duckdb
15
+ *.sqlite3
16
+ .mypy_cache/
17
+ .ruff_cache/
18
+ .pytest_cache/
19
+ htmlcov/
20
+ .coverage
21
+ .coverage.*
22
+ *.log
23
+ .DS_Store
24
+ .claude/
25
+ security/
26
+ infra/
27
+ site/
28
+ scripts/
29
+ .mcpregistry_github_token
30
+ .mcpregistry_registry_token
31
+ _*/
32
+ blog/
33
+ review*
34
+ design/
35
+ examples/test*
@@ -0,0 +1,104 @@
1
+ # ob-snowflake — OrionBelt Semantic Layer Driver for Snowflake
2
+
3
+ ## Purpose
4
+
5
+ PEP 249 DB-API 2.0 driver wrapping `snowflake-connector-python = ">=3.0"` that intercepts OBML YAML
6
+ queries, compiles them to snowflake SQL via the OrionBelt CompilationPipeline
7
+ (direct import) or OB REST API (standalone), and executes them natively.
8
+
9
+ **OB dialect string:** `"snowflake"`
10
+ **Author:** Ralf Becher / RALFORION d.o.o. (info@orionbelt.ai)
11
+ **License:** Apache 2.0
12
+
13
+ ---
14
+
15
+ ## Module Map
16
+
17
+ | File | Responsibility |
18
+ |---|---|
19
+ | `__init__.py` | PEP 249 connect() + module constants |
20
+ | `connection.py` | Connection class |
21
+ | `cursor.py` | Cursor class — OBML detection + execution |
22
+ | `compiler.py` | Direct OB import or REST fallback |
23
+ | `exceptions.py` | PEP 249 exception hierarchy |
24
+ | `type_codes.py` | PEP 249 type objects |
25
+
26
+ ---
27
+
28
+ ## connect() Parameters
29
+
30
+ ### snowflake-specific
31
+ | account | str | Snowflake account identifier (e.g. xy12345.eu-west-1) |
32
+ | user | str | Snowflake username |
33
+ | password | str | Snowflake password |
34
+ | database | str | Default database |
35
+ | schema | str | Default schema |
36
+ | warehouse | str | Virtual warehouse |
37
+ | role | str | Snowflake role |
38
+
39
+ ### OrionBelt parameters (same across all vendors)
40
+ | Parameter | Default | Description |
41
+ |---|---|---|
42
+ | ob_model_id | None | Pre-loaded OB model ID |
43
+ | ob_model_yaml | None | OBML YAML string to load |
44
+ | ob_model_file | None | Path to .obml.yaml file |
45
+ | ob_api_url | http://localhost:8000 | OB REST API URL (standalone mode only) |
46
+ | ob_timeout | 30 | HTTP timeout in seconds |
47
+
48
+ ---
49
+
50
+ ## Compiler Bridge (compiler.py)
51
+
52
+ Auto-detects whether OB core is importable (same process as orionbelt-api)
53
+ or whether to fall back to REST:
54
+
55
+ ```python
56
+ def compile_obml(obml: dict, model, dialect: str) -> str:
57
+ try:
58
+ # Direct call — zero overhead, used when embedded in orionbelt-api
59
+ from orionbelt.compiler.pipeline import CompilationPipeline
60
+ result = CompilationPipeline().compile(obml, model, dialect)
61
+ return result.sql
62
+ except ImportError:
63
+ # Standalone mode — call REST API
64
+ return _compile_via_rest(obml, dialect)
65
+ ```
66
+
67
+ ---
68
+
69
+ ## Vendor-Specific Notes
70
+
71
+ - Auto-commit is ON by default in Snowflake; commit() is a no-op unless autocommit=False
72
+ - executemany() with OBML raises NotSupportedError
73
+ - Use TIMESTAMP_NTZ for timezone-naive datetimes in generated SQL
74
+ - Snowflake identifiers are UPPERCASE by default; OB handles quoting via sqlglot
75
+
76
+ ---
77
+
78
+ ## Type System
79
+
80
+ Use snowflake.connector.cursor().description for column metadata.
81
+ Types map via FIELD_TYPES dict in snowflake.connector.constants.
82
+
83
+ ---
84
+
85
+ ## Build Order
86
+
87
+ Session 1: exceptions.py + type_codes.py + compiler.py + unit tests
88
+ Session 2: connection.py + cursor.py (OBML detection, core execute)
89
+ Session 3: __init__.py + connect() + integration tests
90
+ Session 4: SQLAlchemy dialect (ob+snowflake:// URL scheme)
91
+
92
+ ---
93
+
94
+ ## Dependencies
95
+
96
+ ```toml
97
+ [project.dependencies]
98
+ snowflake-connector-python = ">=3.0"
99
+ pyyaml = ">=6.0"
100
+
101
+ [project.optional-dependencies]
102
+ sqlalchemy = ["sqlalchemy>=2.0"]
103
+ dev = ["pytest>=8.0", "pytest-asyncio>=0.23", "mypy>=1.10", "ruff>=0.4", "respx>=0.21"]
104
+ ```
@@ -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/.
@@ -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,15 @@
1
+ # ob-snowflake
2
+
3
+ OrionBelt Semantic Layer driver for Snowflake (DB-API 2.0)
4
+
5
+ Part of the [OrionBelt Semantic Layer](https://github.com/ralfbecher/orionbelt-semantic-layer) project.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install ob-snowflake
11
+ ```
12
+
13
+ ## License
14
+
15
+ BSL-1.1 — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ob-snowflake"
7
+ version = "0.1.0"
8
+ description = "OrionBelt Semantic Layer driver for Snowflake (DB-API 2.0)"
9
+ license = { text = "BSL-1.1" }
10
+ readme = "README.md"
11
+ authors = [{ name = "Ralf Becher", email = "info@orionbelt.ai" }]
12
+ keywords = ["snowflake", "semantic-layer", "obml", "db-api", "orionbelt"]
13
+ requires-python = ">=3.12"
14
+ dependencies = [
15
+ "ob-driver-core>=0.1",
16
+ "snowflake-connector-python>=3.0",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ sqlalchemy = ["sqlalchemy>=2.0"]
21
+ dev = [
22
+ "pytest>=8.0",
23
+ "pytest-asyncio>=0.23",
24
+ "mypy>=1.10",
25
+ "ruff>=0.4",
26
+ "respx>=0.21",
27
+ ]
28
+
29
+ [project.entry-points."sqlalchemy.dialects"]
30
+ "ob.snowflake" = "ob_snowflake.dialect:OBSnowflakeDialect"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/ob_snowflake"]
34
+
35
+ [tool.ruff]
36
+ line-length = 100
37
+ target-version = "py312"
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I", "UP", "B", "SIM", "ANN"]
41
+
42
+ [tool.mypy]
43
+ python_version = "3.12"
44
+ strict = true
45
+ files = ["src/ob_snowflake"]
46
+
47
+ [tool.pytest.ini_options]
48
+ asyncio_mode = "auto"
49
+ testpaths = ["tests"]
50
+ markers = ["integration: requires live DB + OB API"]
51
+ addopts = "-m 'not integration'"
@@ -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()
@@ -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,382 @@
1
+ """Unit tests for the ob-snowflake DB-API 2.0 driver.
2
+
3
+ All tests mock snowflake-connector-python — no live Snowflake needed.
4
+ OBML tests additionally mock the REST API call to ``/v1/query/sql``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections import namedtuple
10
+ from unittest.mock import MagicMock, patch
11
+
12
+ import pytest
13
+
14
+ import ob_snowflake
15
+ from ob_snowflake.connection import Connection
16
+ from ob_snowflake.cursor import Cursor
17
+ from ob_snowflake.exceptions import NotSupportedError, ProgrammingError
18
+ from ob_snowflake.type_codes import DATETIME, NUMBER, STRING
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Helper to build a mock Snowflake connection
23
+ # ---------------------------------------------------------------------------
24
+
25
+ # snowflake-connector-python description columns are named tuples
26
+ SfColumn = namedtuple("Column", ["name", "type_code", "display_size",
27
+ "internal_size", "precision", "scale", "null_ok"])
28
+
29
+
30
+ def _make_mock_native() -> MagicMock:
31
+ """Return a mock snowflake.connector connection."""
32
+ mock_conn = MagicMock()
33
+ mock_cursor = MagicMock()
34
+ mock_conn.cursor.return_value = mock_cursor
35
+ # Default: no results
36
+ mock_cursor.description = None
37
+ mock_cursor.rowcount = -1
38
+ mock_cursor.fetchone.return_value = None
39
+ mock_cursor.fetchall.return_value = []
40
+ mock_cursor.fetchmany.return_value = []
41
+ return mock_conn
42
+
43
+
44
+ def _mock_api_response(sql: str) -> MagicMock:
45
+ """Create a mock httpx response returning the given SQL."""
46
+ resp = MagicMock()
47
+ resp.is_success = True
48
+ resp.json.return_value = {"sql": sql}
49
+ return resp
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # PEP 249 module-level constants
54
+ # ---------------------------------------------------------------------------
55
+
56
+
57
+ def test_apilevel() -> None:
58
+ assert ob_snowflake.apilevel == "2.0"
59
+
60
+
61
+ def test_threadsafety() -> None:
62
+ assert ob_snowflake.threadsafety == 1
63
+
64
+
65
+ def test_paramstyle() -> None:
66
+ assert ob_snowflake.paramstyle == "pyformat"
67
+
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # connect()
71
+ # ---------------------------------------------------------------------------
72
+
73
+
74
+ def test_connect_returns_connection() -> None:
75
+ with patch("snowflake.connector.connect") as mock_connect:
76
+ mock_connect.return_value = _make_mock_native()
77
+ conn = ob_snowflake.connect(account="xy12345", user="testuser", password="secret")
78
+ assert isinstance(conn, Connection)
79
+ mock_connect.assert_called_once()
80
+ kwargs = mock_connect.call_args.kwargs
81
+ assert kwargs["account"] == "xy12345"
82
+ assert kwargs["user"] == "testuser"
83
+ assert kwargs["password"] == "secret"
84
+
85
+
86
+ def test_connect_with_all_params() -> None:
87
+ with patch("snowflake.connector.connect") as mock_connect:
88
+ mock_connect.return_value = _make_mock_native()
89
+ conn = ob_snowflake.connect(
90
+ account="xy12345.eu-west-1",
91
+ user="me",
92
+ password="pw",
93
+ database="MYDB",
94
+ schema="PUBLIC",
95
+ warehouse="COMPUTE_WH",
96
+ role="SYSADMIN",
97
+ authenticator="externalbrowser",
98
+ )
99
+ assert isinstance(conn, Connection)
100
+ kwargs = mock_connect.call_args.kwargs
101
+ assert kwargs["account"] == "xy12345.eu-west-1"
102
+ assert kwargs["database"] == "MYDB"
103
+ assert kwargs["schema"] == "PUBLIC"
104
+ assert kwargs["warehouse"] == "COMPUTE_WH"
105
+ assert kwargs["role"] == "SYSADMIN"
106
+ assert kwargs["authenticator"] == "externalbrowser"
107
+
108
+
109
+ def test_connect_context_manager() -> None:
110
+ with patch("snowflake.connector.connect") as mock_connect:
111
+ mock_native = _make_mock_native()
112
+ mock_connect.return_value = mock_native
113
+ with ob_snowflake.connect(account="xy12345") as conn:
114
+ assert isinstance(conn, Connection)
115
+ mock_native.close.assert_called_once()
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # Connection
120
+ # ---------------------------------------------------------------------------
121
+
122
+
123
+ def test_connection_close_is_idempotent() -> None:
124
+ mock_native = _make_mock_native()
125
+ conn = Connection(mock_native)
126
+ conn.close()
127
+ conn.close() # should not raise
128
+ mock_native.close.assert_called_once()
129
+
130
+
131
+ def test_connection_cursor_after_close_raises() -> None:
132
+ mock_native = _make_mock_native()
133
+ conn = Connection(mock_native)
134
+ conn.close()
135
+ with pytest.raises(ProgrammingError, match="closed"):
136
+ conn.cursor()
137
+
138
+
139
+ def test_connection_commit() -> None:
140
+ mock_native = _make_mock_native()
141
+ conn = Connection(mock_native)
142
+ conn.commit()
143
+ mock_native.commit.assert_called_once()
144
+
145
+
146
+ def test_connection_rollback() -> None:
147
+ mock_native = _make_mock_native()
148
+ conn = Connection(mock_native)
149
+ conn.rollback()
150
+ mock_native.rollback.assert_called_once()
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Cursor — plain SQL
155
+ # ---------------------------------------------------------------------------
156
+
157
+
158
+ def test_cursor_execute_calls_native() -> None:
159
+ mock_native = _make_mock_native()
160
+ conn = Connection(mock_native)
161
+ with conn.cursor() as cur:
162
+ cur.execute("SELECT 1")
163
+ mock_native.cursor().execute.assert_called_once_with("SELECT 1")
164
+
165
+
166
+ def test_cursor_execute_with_params() -> None:
167
+ mock_native = _make_mock_native()
168
+ conn = Connection(mock_native)
169
+ with conn.cursor() as cur:
170
+ cur.execute("SELECT %(a)s + %(b)s", {"a": 3, "b": 4})
171
+ mock_native.cursor().execute.assert_called_once_with(
172
+ "SELECT %(a)s + %(b)s", {"a": 3, "b": 4}
173
+ )
174
+
175
+
176
+ def test_cursor_execute_returns_self() -> None:
177
+ mock_native = _make_mock_native()
178
+ conn = Connection(mock_native)
179
+ with conn.cursor() as cur:
180
+ result = cur.execute("SELECT 1")
181
+ assert result is cur
182
+
183
+
184
+ def test_cursor_description() -> None:
185
+ mock_native = _make_mock_native()
186
+ mock_cursor = mock_native.cursor()
187
+ mock_cursor.description = [
188
+ SfColumn("NUM", 0, None, None, None, None, None), # FIXED → NUMBER
189
+ SfColumn("TXT", 2, None, None, None, None, None), # TEXT → STRING
190
+ SfColumn("DT", 4, None, None, None, None, None), # TIMESTAMP_NTZ → DATETIME
191
+ SfColumn("BIN", 11, None, None, None, None, None), # BINARY → BINARY
192
+ SfColumn("BOOL", 13, None, None, None, None, None), # BOOLEAN → STRING
193
+ ]
194
+ conn = Connection(mock_native)
195
+ cur = conn.cursor()
196
+ desc = cur.description
197
+ assert desc is not None
198
+ assert len(desc) == 5
199
+ assert all(len(col) == 7 for col in desc)
200
+ assert desc[0][0] == "NUM"
201
+ assert desc[0][1] == NUMBER
202
+ assert desc[1][0] == "TXT"
203
+ assert desc[1][1] == STRING
204
+ assert desc[2][0] == "DT"
205
+ assert desc[2][1] == DATETIME
206
+ assert desc[4][0] == "BOOL"
207
+ assert desc[4][1] == STRING
208
+
209
+
210
+ def test_cursor_description_none_before_execute() -> None:
211
+ mock_native = _make_mock_native()
212
+ mock_native.cursor().description = None
213
+ conn = Connection(mock_native)
214
+ cur = conn.cursor()
215
+ assert cur.description is None
216
+
217
+
218
+ def test_cursor_fetchone() -> None:
219
+ mock_native = _make_mock_native()
220
+ mock_native.cursor().fetchone.return_value = (42,)
221
+ conn = Connection(mock_native)
222
+ cur = conn.cursor()
223
+ row = cur.fetchone()
224
+ assert row == (42,)
225
+
226
+
227
+ def test_cursor_fetchone_exhausted() -> None:
228
+ mock_native = _make_mock_native()
229
+ mock_native.cursor().fetchone.return_value = None
230
+ conn = Connection(mock_native)
231
+ cur = conn.cursor()
232
+ assert cur.fetchone() is None
233
+
234
+
235
+ def test_cursor_fetchall() -> None:
236
+ mock_native = _make_mock_native()
237
+ mock_native.cursor().fetchall.return_value = [(1, "a"), (2, "b"), (3, "c")]
238
+ conn = Connection(mock_native)
239
+ cur = conn.cursor()
240
+ rows = cur.fetchall()
241
+ assert len(rows) == 3
242
+ assert rows[0] == (1, "a")
243
+
244
+
245
+ def test_cursor_fetchmany() -> None:
246
+ mock_native = _make_mock_native()
247
+ mock_native.cursor().fetchmany.return_value = [(1,), (2,), (3,)]
248
+ conn = Connection(mock_native)
249
+ cur = conn.cursor()
250
+ batch = cur.fetchmany(3)
251
+ assert len(batch) == 3
252
+ mock_native.cursor().fetchmany.assert_called_with(3)
253
+
254
+
255
+ def test_cursor_iteration() -> None:
256
+ mock_native = _make_mock_native()
257
+ mock_native.cursor().fetchone.side_effect = [(0,), (1,), (2,), None]
258
+ conn = Connection(mock_native)
259
+ cur = conn.cursor()
260
+ rows = list(cur)
261
+ assert len(rows) == 3
262
+ assert rows[0] == (0,)
263
+
264
+
265
+ def test_cursor_close_then_fetch_raises() -> None:
266
+ mock_native = _make_mock_native()
267
+ conn = Connection(mock_native)
268
+ cur = conn.cursor()
269
+ cur.close()
270
+ with pytest.raises(ProgrammingError, match="closed"):
271
+ cur.fetchone()
272
+
273
+
274
+ def test_cursor_executemany_plain_sql() -> None:
275
+ mock_native = _make_mock_native()
276
+ conn = Connection(mock_native)
277
+ cur = conn.cursor()
278
+ cur.executemany(
279
+ "INSERT INTO t VALUES (%(id)s, %(name)s)",
280
+ [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}],
281
+ )
282
+ assert mock_native.cursor().execute.call_count == 2
283
+
284
+
285
+ def test_cursor_executemany_obml_raises() -> None:
286
+ mock_native = _make_mock_native()
287
+ conn = Connection(mock_native)
288
+ cur = conn.cursor()
289
+ obml = "select:\n dimensions:\n - Region\n measures:\n - Revenue\n"
290
+ with pytest.raises(NotSupportedError, match="executemany"):
291
+ cur.executemany(obml, [])
292
+
293
+
294
+ def test_cursor_setinputsizes_noop() -> None:
295
+ mock_native = _make_mock_native()
296
+ conn = Connection(mock_native)
297
+ cur = conn.cursor()
298
+ cur.setinputsizes([]) # should not raise
299
+
300
+
301
+ def test_cursor_setoutputsize_noop() -> None:
302
+ mock_native = _make_mock_native()
303
+ conn = Connection(mock_native)
304
+ cur = conn.cursor()
305
+ cur.setoutputsize(1000) # should not raise
306
+
307
+
308
+ def test_cursor_lastrowid_is_none() -> None:
309
+ mock_native = _make_mock_native()
310
+ conn = Connection(mock_native)
311
+ cur = conn.cursor()
312
+ assert cur.lastrowid is None
313
+
314
+
315
+ def test_cursor_rowcount() -> None:
316
+ mock_native = _make_mock_native()
317
+ mock_native.cursor().rowcount = 5
318
+ conn = Connection(mock_native)
319
+ cur = conn.cursor()
320
+ assert cur.rowcount == 5
321
+
322
+
323
+ # ---------------------------------------------------------------------------
324
+ # Cursor — OBML queries (mocked REST API)
325
+ # ---------------------------------------------------------------------------
326
+
327
+
328
+ def test_obml_compile_and_execute() -> None:
329
+ """OBML query is compiled via REST API then executed on Snowflake."""
330
+ mock_native = _make_mock_native()
331
+ compiled_sql = 'SELECT "REGION", SUM("AMOUNT") AS "REVENUE" FROM "ORDERS" GROUP BY "REGION"'
332
+ mock_native.cursor().description = [
333
+ SfColumn("REGION", 2, None, None, None, None, None),
334
+ SfColumn("REVENUE", 1, None, None, None, None, None),
335
+ ]
336
+ mock_native.cursor().fetchall.return_value = [
337
+ ("EMEA", 300.0), ("APAC", 150.0), ("AMER", 550.0),
338
+ ]
339
+ conn = Connection(mock_native)
340
+ with patch("httpx.post", return_value=_mock_api_response(compiled_sql)):
341
+ with conn.cursor() as cur:
342
+ cur.execute("select:\n dimensions:\n - Region\n measures:\n - Revenue\n")
343
+ rows = cur.fetchall()
344
+ assert len(rows) == 3
345
+ # Verify the compiled SQL was passed to native cursor
346
+ mock_native.cursor().execute.assert_called_once_with(compiled_sql)
347
+
348
+
349
+ def test_obml_rest_dialect_is_snowflake() -> None:
350
+ """REST API is called with dialect=snowflake."""
351
+ mock_native = _make_mock_native()
352
+ conn = Connection(mock_native)
353
+ compiled_sql = "SELECT 1"
354
+ with patch("httpx.post", return_value=_mock_api_response(compiled_sql)) as mock_post:
355
+ with conn.cursor() as cur:
356
+ cur.execute("select:\n measures:\n - Revenue\n")
357
+ url = mock_post.call_args.args[0]
358
+ assert "/v1/query/sql" in url
359
+ assert mock_post.call_args.kwargs["params"] == {"dialect": "snowflake"}
360
+
361
+
362
+ def test_obml_custom_api_url() -> None:
363
+ """Custom ob_api_url is forwarded to the REST call."""
364
+ mock_native = _make_mock_native()
365
+ conn = Connection(mock_native, ob_api_url="http://my-api:9000")
366
+ compiled_sql = "SELECT 1"
367
+ with patch("httpx.post", return_value=_mock_api_response(compiled_sql)) as mock_post:
368
+ with conn.cursor() as cur:
369
+ cur.execute("select:\n measures:\n - Revenue\n")
370
+ url = mock_post.call_args.args[0]
371
+ assert url == "http://my-api:9000/v1/query/sql"
372
+
373
+
374
+ def test_plain_sql_passthrough() -> None:
375
+ """Plain SQL is passed through without OBML compilation — no REST call."""
376
+ mock_native = _make_mock_native()
377
+ conn = Connection(mock_native)
378
+ with patch("httpx.post") as mock_post:
379
+ with conn.cursor() as cur:
380
+ cur.execute("SELECT COUNT(*) FROM orders")
381
+ mock_post.assert_not_called()
382
+ mock_native.cursor().execute.assert_called_once_with("SELECT COUNT(*) FROM orders")
@@ -0,0 +1,29 @@
1
+ """Unit tests for OBML YAML detection — no external services required."""
2
+ import pytest
3
+ from ob_snowflake.compiler import is_obml, parse_obml
4
+
5
+
6
+ @pytest.mark.parametrize("query,expected", [
7
+ ("select:\n dimensions:\n - Region\n measures:\n - Revenue\n", True),
8
+ ("select:\n measures:\n - Revenue\n", True),
9
+ ("select:\n dimensions:\n - Country\n", True),
10
+ ("SELECT:\n dimensions:\n - X\n", True),
11
+ (" select:\n dimensions:\n - X\n", True),
12
+ ("SELECT * FROM orders", False),
13
+ ("SELECT id\nFROM customers WHERE id = 1", False),
14
+ ("", False),
15
+ ("model:\n name: test\n", False),
16
+ ("select:\n filters:\n - x = 1\n", False),
17
+ ("select:\n - [unclosed", False),
18
+ ("select:\n - dimension1\n", False),
19
+ ])
20
+ def test_obml_detection(query, expected):
21
+ assert is_obml(query) == expected
22
+
23
+
24
+ def test_parse_obml_returns_dict():
25
+ q = "select:\n dimensions:\n - Region\n measures:\n - Revenue\nlimit: 100\n"
26
+ result = parse_obml(q)
27
+ assert result["select"]["dimensions"] == ["Region"]
28
+ assert result["select"]["measures"] == ["Revenue"]
29
+ assert result["limit"] == 100