qualis-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,44 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ test:
14
+ name: test (Python ${{ matrix.python-version }})
15
+ runs-on: ubuntu-latest
16
+ strategy:
17
+ fail-fast: false
18
+ matrix:
19
+ python-version: ["3.12", "3.13"]
20
+ steps:
21
+ - uses: actions/checkout@v4
22
+
23
+ - name: Set up uv
24
+ uses: astral-sh/setup-uv@v3
25
+ with:
26
+ enable-cache: true
27
+
28
+ - name: Set up Python ${{ matrix.python-version }}
29
+ run: uv python install ${{ matrix.python-version }}
30
+
31
+ - name: Install dependencies
32
+ run: uv sync --dev
33
+
34
+ - name: Lint with ruff
35
+ run: uv run ruff check src/ tests/
36
+
37
+ - name: Typecheck with mypy
38
+ run: uv run mypy src/
39
+
40
+ - name: Run tests
41
+ run: uv run pytest --cov=qualis_snowflake --cov-report=term-missing
42
+
43
+ - name: Enforce coverage threshold
44
+ run: uv run pytest --cov=qualis_snowflake --cov-fail-under=70
@@ -0,0 +1,60 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ build:
13
+ name: Build sdist and wheel
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+
18
+ - name: Set up uv
19
+ uses: astral-sh/setup-uv@v3
20
+
21
+ - name: Set up Python
22
+ run: uv python install 3.12
23
+
24
+ - name: Build artefacts
25
+ run: uv build
26
+
27
+ - name: Verify version matches tag
28
+ run: |
29
+ VERSION_IN_PYPROJECT=$(grep '^version = ' pyproject.toml | head -1 | sed 's/.*"\(.*\)"/\1/')
30
+ TAG_VERSION="${GITHUB_REF#refs/tags/v}"
31
+ if [ "$VERSION_IN_PYPROJECT" != "$TAG_VERSION" ]; then
32
+ echo "Version mismatch: pyproject.toml says '$VERSION_IN_PYPROJECT', tag is '$TAG_VERSION'"
33
+ exit 1
34
+ fi
35
+ echo "Version $VERSION_IN_PYPROJECT matches tag v$TAG_VERSION"
36
+
37
+ - name: Upload artefacts
38
+ uses: actions/upload-artifact@v4
39
+ with:
40
+ name: dist
41
+ path: dist/
42
+
43
+ publish:
44
+ name: Publish to PyPI
45
+ needs: build
46
+ runs-on: ubuntu-latest
47
+ environment:
48
+ name: pypi
49
+ url: https://pypi.org/p/qualis-snowflake
50
+ permissions:
51
+ id-token: write
52
+ steps:
53
+ - name: Download artefacts
54
+ uses: actions/download-artifact@v4
55
+ with:
56
+ name: dist
57
+ path: dist/
58
+
59
+ - name: Publish to PyPI
60
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.so
4
+ .venv/
5
+ venv/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+ .coverage
13
+ htmlcov/
14
+ .env
15
+ *.log
16
+ .DS_Store
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,176 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of recording
55
+ instructions given to the Licensor.
56
+
57
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
58
+ whom a Contribution has been received by the Licensor and is included
59
+ in the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ copyright license to reproduce, prepare Derivative Works of,
65
+ publicly display, publicly perform, sublicense, and distribute the
66
+ Work and such Derivative Works in Source or Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ (except as stated in this section) patent license to make, have made,
72
+ use, offer to sell, sell, import, and otherwise transfer the Work,
73
+ where such license applies only to those Contributions necessary to
74
+ make, use, sell, offer to sell, import, or otherwise transfer the Work.
75
+
76
+ 4. Redistribution. You may reproduce and distribute copies of the
77
+ Work or Derivative Works thereof in any medium, with or without
78
+ modifications, and in Source or Object form, provided that You
79
+ meet the following conditions:
80
+
81
+ (a) You must give any other recipients of the Work or Derivative
82
+ Works a copy of this License; and
83
+
84
+ (b) You must reproduce the above copyright notices for use,
85
+ reproduction, and distribution, and a relevant copyright notice
86
+ in the Derivative Works; and
87
+
88
+ (c) You must retain, in the Source form of any Derivative Works
89
+ that You distribute, all copyright, patent, trademark, and
90
+ attribution notices from the Source form of the Work,
91
+ excluding those notices that do not pertain to any part of
92
+ the Derivative Works; and
93
+
94
+ (d) If the Work includes a "NOTICE" text file, the contents
95
+ of the NOTICE file are for informational purposes only
96
+ and do not modify the License. You may add Your own attribution
97
+ notices within Derivative Works that You distribute, alongside
98
+ or in addition to the NOTICE text from the Work, provided
99
+ that such additional attribution notices cannot be construed
100
+ as modifying the License.
101
+
102
+ You may add Your own license statement for Your modifications and
103
+ may provide additional grant of rights to use, copy, modify, merge,
104
+ publish, distribute, sublicense, and/or sell copies of the Work.
105
+
106
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
107
+ any Contribution intentionally submitted for inclusion in the Work
108
+ by You to the Licensor shall be under the terms and conditions of
109
+ this License, without any additional terms or conditions.
110
+ Notwithstanding the above, nothing herein shall supersede or modify
111
+ the terms of any separate license agreement you may have executed
112
+ with Licensor regarding such Contributions.
113
+
114
+ 6. Trademarks. This License does not grant permission to use the trade
115
+ names, trademarks, service marks, or product names of the Licensor,
116
+ except as required for reasonable and customary use in describing the
117
+ origin of the Work and reproducing the content of the NOTICE file.
118
+
119
+ 7. Disclaimer of Warranty. Unless required by applicable law or
120
+ agreed to in writing, Licensor provides the Work (and each
121
+ Contributor provides its Contributions) on an "AS IS" BASIS,
122
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
123
+ implied, including, without limitation, any warranties or conditions
124
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
125
+ PARTICULAR PURPOSE. You are solely responsible for determining the
126
+ appropriateness of using or reproducing the Work and assume any
127
+ risks associated with Your exercise of permissions under this License.
128
+
129
+ 8. Limitation of Liability. In no event and under no legal theory,
130
+ whether in tort (including negligence), contract, or otherwise,
131
+ unless required by applicable law (such as deliberate and grossly
132
+ negligent acts) or agreed to in writing, shall any Contributor be
133
+ liable to You for damages, including any direct, indirect, special,
134
+ incidental, or exemplary damages of any character arising as a
135
+ result of this License or out of the use or inability to use the
136
+ Work (including but not limited to damages for loss of goodwill,
137
+ work stoppage, computer failure or malfunction, or all other
138
+ commercial damages or losses), even if such Contributor has been
139
+ advised of the possibility of such damages.
140
+
141
+ 9. Accepting Warranty or Additional Liability. While redistributing
142
+ the Work or Derivative Works thereof, You may choose to offer,
143
+ and charge a fee for, acceptance of support, warranty, indemnity,
144
+ or other liability obligations and/or rights consistent with this
145
+ License. However, in accepting such obligations, You may offer only
146
+ conditions that are consistent with this full terms and conditions,
147
+ including warranty disclaimers and limitation of liability contained
148
+ in this License, or any of the terms and conditions contained in a
149
+ Section 9 of the License, including without limitation
150
+ indemnification.
151
+
152
+ END OF TERMS AND CONDITIONS
153
+
154
+ APPENDIX: How to apply the Apache License to your work.
155
+
156
+ To apply the Apache License to your work, attach the following
157
+ boilerplate notice, with the fields enclosed by brackets "[]"
158
+ replaced with your own identifying information. (Don't include
159
+ the brackets!) The text should be enclosed in the appropriate
160
+ comment syntax for the format of the file. We also recommend that
161
+ a file or directory name be given, with a reference to where the
162
+ full text can be found.
163
+
164
+ Copyright 2024 Ahmed Ashraf
165
+
166
+ Licensed under the Apache License, Version 2.0 (the "License");
167
+ you may not use this file except in compliance with the License.
168
+ You may obtain a copy of the License at
169
+
170
+ http://www.apache.org/licenses/LICENSE-2.0
171
+
172
+ Unless required by applicable law or agreed to in writing, software
173
+ distributed under the License is distributed on an "AS IS" BASIS,
174
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
175
+ See the License for the specific language governing permissions and
176
+ limitations under the License.
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.4
2
+ Name: qualis-snowflake
3
+ Version: 0.1.0
4
+ Summary: Snowflake adapter for Qualis (data quality framework)
5
+ Project-URL: Homepage, https://github.com/ahmedashraffcih/qualis-snowflake
6
+ Project-URL: Repository, https://github.com/ahmedashraffcih/qualis-snowflake
7
+ Project-URL: Issues, https://github.com/ahmedashraffcih/qualis-snowflake/issues
8
+ Author-email: Ahmed Ashraf <ahmedashraffcih@gmail.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: data-quality,dq,qualis,snowflake
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Database
19
+ Classifier: Topic :: Software Development :: Quality Assurance
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: qualis>=0.3.1
23
+ Requires-Dist: snowflake-connector-python>=3.0
24
+ Description-Content-Type: text/markdown
25
+
26
+ # qualis-snowflake
27
+
28
+ Snowflake adapter for [Qualis](https://github.com/ahmedashraffcih/qualis) —
29
+ the open-source data quality framework.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install qualis qualis-snowflake
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ```yaml
40
+ # qualis.yaml
41
+ adapter: snowflake
42
+ database_url: "snowflake://user:password@account/db/schema?warehouse=wh&role=role"
43
+ ```
44
+
45
+ ```bash
46
+ qualis check --rules rules/ --sample your_table
47
+ ```
48
+
49
+ ## Supported checks
50
+
51
+ - not_null
52
+ - unique
53
+ - between
54
+ - regex
55
+ - in_set
56
+ - row_count
57
+ - not_negative
58
+ - reference_lookup
59
+
60
+ All queries run in a read-only transaction.
61
+
62
+ ## License
63
+
64
+ Apache 2.0.
@@ -0,0 +1,39 @@
1
+ # qualis-snowflake
2
+
3
+ Snowflake adapter for [Qualis](https://github.com/ahmedashraffcih/qualis) —
4
+ the open-source data quality framework.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pip install qualis qualis-snowflake
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```yaml
15
+ # qualis.yaml
16
+ adapter: snowflake
17
+ database_url: "snowflake://user:password@account/db/schema?warehouse=wh&role=role"
18
+ ```
19
+
20
+ ```bash
21
+ qualis check --rules rules/ --sample your_table
22
+ ```
23
+
24
+ ## Supported checks
25
+
26
+ - not_null
27
+ - unique
28
+ - between
29
+ - regex
30
+ - in_set
31
+ - row_count
32
+ - not_negative
33
+ - reference_lookup
34
+
35
+ All queries run in a read-only transaction.
36
+
37
+ ## License
38
+
39
+ Apache 2.0.
@@ -0,0 +1,62 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "qualis-snowflake"
7
+ version = "0.1.0"
8
+ description = "Snowflake adapter for Qualis (data quality framework)"
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ requires-python = ">=3.12"
12
+ authors = [
13
+ { name = "Ahmed Ashraf", email = "ahmedashraffcih@gmail.com" },
14
+ ]
15
+ keywords = ["data-quality", "snowflake", "qualis", "dq"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Database",
24
+ "Topic :: Software Development :: Quality Assurance",
25
+ "Typing :: Typed",
26
+ ]
27
+ dependencies = [
28
+ "qualis>=0.3.1",
29
+ "snowflake-connector-python>=3.0",
30
+ ]
31
+
32
+ [project.entry-points."qualis.adapters"]
33
+ snowflake = "qualis_snowflake.adapter:SnowflakeAdapter"
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/ahmedashraffcih/qualis-snowflake"
37
+ Repository = "https://github.com/ahmedashraffcih/qualis-snowflake"
38
+ Issues = "https://github.com/ahmedashraffcih/qualis-snowflake/issues"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/qualis_snowflake"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
45
+
46
+ [tool.mypy]
47
+ strict = true
48
+ python_version = "3.12"
49
+
50
+ [tool.ruff]
51
+ line-length = 100
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "F", "I", "B", "UP", "RUF", "TC"]
55
+
56
+ [dependency-groups]
57
+ dev = [
58
+ "mypy>=1.0",
59
+ "pytest>=8.0",
60
+ "pytest-cov>=4.0",
61
+ "ruff>=0.5",
62
+ ]
@@ -0,0 +1,9 @@
1
+ """Snowflake adapter for Qualis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ from qualis_snowflake.adapter import SnowflakeAdapter
8
+
9
+ __all__ = ["SnowflakeAdapter", "__version__"]
@@ -0,0 +1,236 @@
1
+ """SnowflakeAdapter implementing qualis.ports.database.DatabasePort.
2
+
3
+ All DQ check queries run inside a read-only transaction to prevent
4
+ accidental writes against production warehouses.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from qualis_snowflake.sql_templates import (
12
+ BETWEEN_SQL,
13
+ IN_SET_SQL,
14
+ NOT_NEGATIVE_SQL,
15
+ NOT_NULL_SQL,
16
+ REFERENCE_LOOKUP_SQL,
17
+ REGEX_SQL,
18
+ ROW_COUNT_SQL,
19
+ TABLE_EXISTS_SQL,
20
+ UNIQUE_SQL,
21
+ )
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Iterator
25
+
26
+
27
+ def _qualified(schema: str, table: str) -> str:
28
+ """Return a double-quoted schema-qualified table reference for Snowflake."""
29
+ if schema:
30
+ return f'"{schema}"."{table}"'
31
+ return f'"{table}"'
32
+
33
+
34
+ def _quote_list(values: list[str]) -> str:
35
+ """Build a SQL literal list for IN(...) substitution.
36
+
37
+ Snowflake supports parameter-bound IN lists in some drivers but not all;
38
+ quoting inline keeps us driver-agnostic. Single quotes are escaped by
39
+ doubling, which is the standard SQL escape for single-quoted literals.
40
+ """
41
+ if not values:
42
+ return "NULL"
43
+ escaped = [v.replace("'", "''") for v in values]
44
+ return ", ".join(f"'{v}'" for v in escaped)
45
+
46
+
47
+ class SnowflakeAdapter:
48
+ """Implements DatabasePort against a Snowflake warehouse."""
49
+
50
+ def __init__(self, connection_url: str) -> None:
51
+ """Construct an adapter from a snowflake://… URL.
52
+
53
+ URL form: ``snowflake://user:password@account/db/schema?warehouse=wh&role=role``.
54
+ Lazily imports ``snowflake.connector`` so a ``pip install
55
+ qualis-snowflake`` without Snowflake credentials still imports the
56
+ module (useful for static analysis on developer machines that
57
+ don't have a warehouse to point at).
58
+ """
59
+ self._connection_url = connection_url
60
+ self._conn: Any = None
61
+
62
+ def _connect(self) -> Any:
63
+ if self._conn is None:
64
+ import snowflake.connector
65
+ self._conn = snowflake.connector.connect(
66
+ **self._parse_url(self._connection_url),
67
+ )
68
+ return self._conn
69
+
70
+ @staticmethod
71
+ def _parse_url(url: str) -> dict[str, str]:
72
+ """Parse a snowflake:// URL into connector kwargs."""
73
+ from urllib.parse import parse_qs, urlparse
74
+ parsed = urlparse(url)
75
+ if parsed.scheme != "snowflake":
76
+ raise ValueError(
77
+ f"SnowflakeAdapter requires snowflake:// URL, got {parsed.scheme!r}"
78
+ )
79
+ path_parts = parsed.path.lstrip("/").split("/")
80
+ query_params = {k: v[0] for k, v in parse_qs(parsed.query).items()}
81
+ return {
82
+ "user": parsed.username or "",
83
+ "password": parsed.password or "",
84
+ "account": parsed.hostname or "",
85
+ "database": path_parts[0] if len(path_parts) > 0 else "",
86
+ "schema": path_parts[1] if len(path_parts) > 1 else "",
87
+ **query_params,
88
+ }
89
+
90
+ # ------------------------------------------------------------------
91
+ # DatabasePort methods
92
+ # ------------------------------------------------------------------
93
+
94
+ def query(
95
+ self, sql: str, params: dict[str, Any] | None = None,
96
+ ) -> list[dict[str, Any]]:
97
+ conn = self._connect()
98
+ with conn.cursor() as cur:
99
+ cur.execute(sql, params or {})
100
+ columns = [d[0].lower() for d in cur.description]
101
+ return [dict(zip(columns, row, strict=True)) for row in cur.fetchall()]
102
+
103
+ def execute(self, sql: str, params: dict[str, Any] | None = None) -> int:
104
+ conn = self._connect()
105
+ with conn.cursor() as cur:
106
+ cur.execute(sql, params or {})
107
+ return cur.rowcount if cur.rowcount is not None else 0
108
+
109
+ def stream(
110
+ self, sql: str, params: dict[str, Any] | None = None,
111
+ chunk_size: int = 10_000,
112
+ ) -> Iterator[list[dict[str, Any]]]:
113
+ conn = self._connect()
114
+ with conn.cursor() as cur:
115
+ cur.execute(sql, params or {})
116
+ columns = [d[0].lower() for d in cur.description]
117
+ while True:
118
+ rows = cur.fetchmany(chunk_size)
119
+ if not rows:
120
+ break
121
+ yield [dict(zip(columns, row, strict=True)) for row in rows]
122
+
123
+ def table_exists(self, schema: str, table: str) -> bool:
124
+ rows = self._query_read_only(
125
+ TABLE_EXISTS_SQL,
126
+ {"schema": schema.upper(), "table": table.upper()},
127
+ )
128
+ if not rows:
129
+ return False
130
+ count_value = next(iter(rows[0].values()))
131
+ return int(count_value) > 0
132
+
133
+ # All check methods run inside a READ ONLY transaction
134
+ def check_not_null(self, schema: str, table: str, column: str) -> dict[str, int]:
135
+ sql = NOT_NULL_SQL.format(column=column, table=_qualified(schema, table))
136
+ row = self._fetch_one_read_only(sql)
137
+ return {"null_count": int(row[0]), "total_count": int(row[1])}
138
+
139
+ def check_unique(self, schema: str, table: str, column: str) -> dict[str, int]:
140
+ sql = UNIQUE_SQL.format(column=column, table=_qualified(schema, table))
141
+ dup_row = self._fetch_one_read_only(sql)
142
+ total_row = self._fetch_one_read_only(
143
+ f"SELECT COUNT(*) FROM {_qualified(schema, table)}"
144
+ )
145
+ return {
146
+ "duplicate_count": int(dup_row[0]) if dup_row else 0,
147
+ "total_count": int(total_row[0]) if total_row else 0,
148
+ }
149
+
150
+ def check_between(
151
+ self, schema: str, table: str, column: str,
152
+ min_val: str, max_val: str,
153
+ ) -> dict[str, int]:
154
+ sql = BETWEEN_SQL.format(column=column, table=_qualified(schema, table))
155
+ row = self._fetch_one_read_only(sql, {"min": min_val, "max": max_val})
156
+ return {
157
+ "out_of_range_count": int(row[0]),
158
+ "total_count": int(row[1]),
159
+ "checked": int(row[2]),
160
+ }
161
+
162
+ def check_regex(
163
+ self, schema: str, table: str, column: str, pattern: str,
164
+ ) -> dict[str, int]:
165
+ sql = REGEX_SQL.format(column=column, table=_qualified(schema, table))
166
+ row = self._fetch_one_read_only(sql, {"pattern": pattern})
167
+ return {"non_matching_count": int(row[0]), "total_count": int(row[1])}
168
+
169
+ def check_in_set(
170
+ self, schema: str, table: str, column: str, values: list[str],
171
+ ) -> dict[str, int]:
172
+ sql = IN_SET_SQL.format(
173
+ column=column, table=_qualified(schema, table),
174
+ value_list=_quote_list(values),
175
+ )
176
+ row = self._fetch_one_read_only(sql)
177
+ return {"invalid_count": int(row[0]), "total_count": int(row[1])}
178
+
179
+ def check_row_count(self, schema: str, table: str) -> dict[str, int]:
180
+ sql = ROW_COUNT_SQL.format(table=_qualified(schema, table))
181
+ row = self._fetch_one_read_only(sql)
182
+ return {"row_count": int(row[0]) if row else 0}
183
+
184
+ def check_not_negative(
185
+ self, schema: str, table: str, column: str,
186
+ ) -> dict[str, int]:
187
+ sql = NOT_NEGATIVE_SQL.format(column=column, table=_qualified(schema, table))
188
+ row = self._fetch_one_read_only(sql)
189
+ return {"negative_count": int(row[0]), "total_count": int(row[1])}
190
+
191
+ def check_reference_lookup(
192
+ self, schema: str, table: str, column: str,
193
+ valid_values: list[str],
194
+ ) -> dict[str, int]:
195
+ sql = REFERENCE_LOOKUP_SQL.format(
196
+ column=column, table=_qualified(schema, table),
197
+ value_list=_quote_list(valid_values),
198
+ )
199
+ row = self._fetch_one_read_only(sql)
200
+ return {"invalid_count": int(row[0]), "total_count": int(row[1])}
201
+
202
+ def close(self) -> None:
203
+ if self._conn is not None:
204
+ self._conn.close()
205
+ self._conn = None
206
+
207
+ # ------------------------------------------------------------------
208
+ # Private helpers
209
+ # ------------------------------------------------------------------
210
+
211
+ def _fetch_one_read_only(
212
+ self, sql: str, params: dict[str, Any] | None = None,
213
+ ) -> tuple[Any, ...]:
214
+ conn = self._connect()
215
+ with conn.cursor() as cur:
216
+ cur.execute("BEGIN READ ONLY")
217
+ try:
218
+ cur.execute(sql, params or {})
219
+ row = cur.fetchone()
220
+ finally:
221
+ cur.execute("ROLLBACK")
222
+ return row if row is not None else ()
223
+
224
+ def _query_read_only(
225
+ self, sql: str, params: dict[str, Any] | None = None,
226
+ ) -> list[dict[str, Any]]:
227
+ conn = self._connect()
228
+ with conn.cursor() as cur:
229
+ cur.execute("BEGIN READ ONLY")
230
+ try:
231
+ cur.execute(sql, params or {})
232
+ columns = [d[0].lower() for d in cur.description]
233
+ rows = cur.fetchall()
234
+ finally:
235
+ cur.execute("ROLLBACK")
236
+ return [dict(zip(columns, row, strict=True)) for row in rows]
File without changes
@@ -0,0 +1,85 @@
1
+ """Snowflake-dialect SQL templates for Qualis check types.
2
+
3
+ Differences from Postgres / DuckDB:
4
+ - Regex uses ``RLIKE`` (not ``~`` and not ``REGEXP_MATCHES``).
5
+ - Parameter style is ``%(name)s`` (matches psycopg / Postgres).
6
+ - ``IN (...)`` literal lists used for in_set and reference_lookup
7
+ (Snowflake supports ``IN (?, ?, ...)`` but not ``= ANY(?)``).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ NOT_NULL_SQL = """
13
+ SELECT
14
+ COUNT(*) FILTER (WHERE "{column}" IS NULL) AS null_count,
15
+ COUNT(*) AS total_count
16
+ FROM {table}
17
+ """
18
+
19
+ UNIQUE_SQL = """
20
+ SELECT COUNT(*) AS duplicate_count
21
+ FROM (
22
+ SELECT "{column}"
23
+ FROM {table}
24
+ WHERE "{column}" IS NOT NULL
25
+ GROUP BY "{column}"
26
+ HAVING COUNT(*) > 1
27
+ ) sub
28
+ """
29
+
30
+ BETWEEN_SQL = """
31
+ SELECT
32
+ COUNT(*) FILTER (
33
+ WHERE "{column}" IS NOT NULL
34
+ AND ("{column}"::text < %(min)s OR "{column}"::text > %(max)s)
35
+ ) AS out_of_range_count,
36
+ COUNT(*) AS total_count,
37
+ COUNT(*) FILTER (WHERE "{column}" IS NOT NULL) AS checked
38
+ FROM {table}
39
+ """
40
+
41
+ REGEX_SQL = """
42
+ SELECT
43
+ COUNT(*) FILTER (
44
+ WHERE "{column}" IS NOT NULL
45
+ AND NOT ("{column}"::text RLIKE %(pattern)s)
46
+ ) AS non_matching_count,
47
+ COUNT(*) AS total_count
48
+ FROM {table}
49
+ """
50
+
51
+ IN_SET_SQL = """
52
+ SELECT
53
+ COUNT(*) FILTER (
54
+ WHERE "{column}" IS NULL
55
+ OR "{column}"::text NOT IN ({value_list})
56
+ ) AS invalid_count,
57
+ COUNT(*) AS total_count
58
+ FROM {table}
59
+ """
60
+
61
+ ROW_COUNT_SQL = """
62
+ SELECT COUNT(*) AS row_count FROM {table}
63
+ """
64
+
65
+ NOT_NEGATIVE_SQL = """
66
+ SELECT
67
+ COUNT(*) FILTER (WHERE "{column}" IS NOT NULL AND "{column}" < 0) AS negative_count,
68
+ COUNT(*) AS total_count
69
+ FROM {table}
70
+ """
71
+
72
+ REFERENCE_LOOKUP_SQL = """
73
+ SELECT
74
+ COUNT(*) FILTER (
75
+ WHERE "{column}" IS NOT NULL
76
+ AND "{column}"::text NOT IN ({value_list})
77
+ ) AS invalid_count,
78
+ COUNT(*) AS total_count
79
+ FROM {table}
80
+ """
81
+
82
+ TABLE_EXISTS_SQL = """
83
+ SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
84
+ WHERE TABLE_SCHEMA = %(schema)s AND TABLE_NAME = %(table)s
85
+ """
File without changes
File without changes
@@ -0,0 +1,117 @@
1
+ """Integration tests with mocked snowflake-connector-python.
2
+
3
+ These tests assert SQL is issued correctly without requiring a live
4
+ Snowflake account.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+ from unittest.mock import MagicMock, patch
11
+
12
+ import pytest
13
+
14
+
15
+ @pytest.fixture
16
+ def mock_snowflake() -> Any:
17
+ """Patch snowflake.connector and yield the mock cursor."""
18
+ with patch("snowflake.connector.connect") as mock_connect:
19
+ mock_conn = MagicMock()
20
+ mock_cursor = MagicMock()
21
+ mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
22
+ mock_connect.return_value = mock_conn
23
+ yield mock_cursor
24
+
25
+
26
+ def test_check_not_null_issues_expected_sql(mock_snowflake: MagicMock) -> None:
27
+ from qualis_snowflake.adapter import SnowflakeAdapter
28
+
29
+ mock_snowflake.fetchone.return_value = (5, 100)
30
+ adapter = SnowflakeAdapter("snowflake://u:p@account/db/schema?warehouse=wh")
31
+ result = adapter.check_not_null("PUBLIC", "USERS", "email")
32
+ assert result == {"null_count": 5, "total_count": 100}
33
+
34
+ all_sql = [call.args[0] for call in mock_snowflake.execute.call_args_list]
35
+ check_sqls = [s for s in all_sql if "null_count" in s.lower()]
36
+ assert any('"email" IS NULL' in s for s in check_sqls)
37
+ assert any('"PUBLIC"."USERS"' in s for s in check_sqls)
38
+
39
+
40
+ def test_check_regex_uses_rlike(mock_snowflake: MagicMock) -> None:
41
+ from qualis_snowflake.adapter import SnowflakeAdapter
42
+
43
+ mock_snowflake.fetchone.return_value = (3, 50)
44
+ adapter = SnowflakeAdapter("snowflake://u:p@account/db/schema")
45
+ result = adapter.check_regex("PUBLIC", "USERS", "email", r"^.+@.+$")
46
+ assert result == {"non_matching_count": 3, "total_count": 50}
47
+
48
+ all_sql = [call.args[0] for call in mock_snowflake.execute.call_args_list]
49
+ assert any("RLIKE" in s.upper() for s in all_sql), (
50
+ "Snowflake regex must use RLIKE, not ~ (Postgres) or "
51
+ "REGEXP_MATCHES (DuckDB)"
52
+ )
53
+
54
+
55
+ def test_check_in_set_inlines_quoted_values(mock_snowflake: MagicMock) -> None:
56
+ from qualis_snowflake.adapter import SnowflakeAdapter
57
+
58
+ mock_snowflake.fetchone.return_value = (1, 10)
59
+ adapter = SnowflakeAdapter("snowflake://u:p@account/db/schema")
60
+ result = adapter.check_in_set(
61
+ "PUBLIC", "ORDERS", "status",
62
+ ["pending", "shipped", "delivered"],
63
+ )
64
+ assert result == {"invalid_count": 1, "total_count": 10}
65
+
66
+ all_sql = [call.args[0] for call in mock_snowflake.execute.call_args_list]
67
+ check_sqls = [s for s in all_sql if "invalid_count" in s.lower()]
68
+ assert any(
69
+ "'pending'" in s and "'shipped'" in s and "'delivered'" in s
70
+ for s in check_sqls
71
+ )
72
+
73
+
74
+ def test_check_in_set_escapes_single_quotes(mock_snowflake: MagicMock) -> None:
75
+ """A status value containing a single quote must be SQL-escaped."""
76
+ from qualis_snowflake.adapter import SnowflakeAdapter
77
+
78
+ mock_snowflake.fetchone.return_value = (0, 1)
79
+ adapter = SnowflakeAdapter("snowflake://u:p@account/db/schema")
80
+ adapter.check_in_set("PUBLIC", "ORDERS", "status", ["o'malley"])
81
+
82
+ all_sql = [call.args[0] for call in mock_snowflake.execute.call_args_list]
83
+ check_sqls = [s for s in all_sql if "invalid_count" in s.lower()]
84
+ assert any("'o''malley'" in s for s in check_sqls)
85
+
86
+
87
+ def test_check_methods_run_in_read_only_transaction(mock_snowflake: MagicMock) -> None:
88
+ """Practitioner / security review: write protection on production warehouses."""
89
+ from qualis_snowflake.adapter import SnowflakeAdapter
90
+
91
+ mock_snowflake.fetchone.return_value = (0, 100)
92
+ adapter = SnowflakeAdapter("snowflake://u:p@account/db/schema")
93
+ adapter.check_not_null("PUBLIC", "USERS", "email")
94
+
95
+ all_sql = [call.args[0] for call in mock_snowflake.execute.call_args_list]
96
+ assert any("BEGIN READ ONLY" in s.upper() for s in all_sql)
97
+ assert any("ROLLBACK" in s.upper() for s in all_sql)
98
+
99
+
100
+ def test_check_reference_lookup_inlines_values(mock_snowflake: MagicMock) -> None:
101
+ from qualis_snowflake.adapter import SnowflakeAdapter
102
+
103
+ mock_snowflake.fetchone.return_value = (2, 50)
104
+ adapter = SnowflakeAdapter("snowflake://u:p@account/db/schema")
105
+ result = adapter.check_reference_lookup(
106
+ "PUBLIC", "ORDERS", "country_code", ["US", "GB", "DE"],
107
+ )
108
+ assert result == {"invalid_count": 2, "total_count": 50}
109
+
110
+
111
+ def test_constructor_rejects_non_snowflake_url() -> None:
112
+ """URL validation happens on first connect, before any credentials are dispatched."""
113
+ from qualis_snowflake.adapter import SnowflakeAdapter
114
+
115
+ with pytest.raises(ValueError, match="snowflake://"):
116
+ adapter = SnowflakeAdapter("postgres://x")
117
+ adapter.check_not_null("a", "b", "c")
File without changes
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import pytest
4
+
5
+
6
+ def test_adapter_can_be_imported() -> None:
7
+ from qualis_snowflake.adapter import SnowflakeAdapter
8
+ assert SnowflakeAdapter is not None
9
+
10
+
11
+ def test_adapter_satisfies_database_port_at_class_level() -> None:
12
+ """SnowflakeAdapter must have all DatabasePort methods.
13
+
14
+ Protocols are structural; this test asserts the methods exist with the
15
+ right names so type-checking at call sites works.
16
+ """
17
+ from qualis_snowflake.adapter import SnowflakeAdapter
18
+
19
+ expected_methods = {
20
+ "query", "execute", "stream", "table_exists",
21
+ "check_not_null", "check_unique", "check_between", "check_regex",
22
+ "check_in_set", "check_row_count", "check_not_negative",
23
+ "check_reference_lookup",
24
+ }
25
+ actual_methods = {m for m in dir(SnowflakeAdapter) if not m.startswith("_")}
26
+ missing = expected_methods - actual_methods
27
+ assert not missing, f"SnowflakeAdapter is missing methods: {missing}"
28
+
29
+
30
+ def test_adapter_constructor_requires_connection_url() -> None:
31
+ from qualis_snowflake.adapter import SnowflakeAdapter
32
+ with pytest.raises(TypeError):
33
+ SnowflakeAdapter() # type: ignore[call-arg]
34
+
35
+
36
+ def test_adapter_satisfies_database_port_protocol_at_runtime() -> None:
37
+ """A SnowflakeAdapter instance must be assignable to a DatabasePort variable.
38
+
39
+ This is the strongest conformance signal — if the Protocol changes in
40
+ a future qualis release, this test fails.
41
+ """
42
+ # DatabasePort is used as a type annotation; under `from __future__ import
43
+ # annotations` the annotation is a string at runtime, but we want mypy
44
+ # to actually verify the assignment. Hide the import from ruff TC002
45
+ # since the import IS load-bearing for mypy.
46
+ from qualis.ports.database import DatabasePort # noqa: TC002
47
+
48
+ from qualis_snowflake.adapter import SnowflakeAdapter
49
+
50
+ adapter: DatabasePort = SnowflakeAdapter(
51
+ "snowflake://u:p@account/db/schema?warehouse=wh"
52
+ )
53
+ # Existence check (no calls — they would need a real connection)
54
+ assert adapter is not None
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ from qualis_snowflake.sql_templates import (
4
+ BETWEEN_SQL,
5
+ IN_SET_SQL,
6
+ NOT_NEGATIVE_SQL,
7
+ NOT_NULL_SQL,
8
+ REFERENCE_LOOKUP_SQL,
9
+ REGEX_SQL,
10
+ ROW_COUNT_SQL,
11
+ TABLE_EXISTS_SQL,
12
+ UNIQUE_SQL,
13
+ )
14
+
15
+
16
+ def test_not_null_uses_count_filter() -> None:
17
+ sql = NOT_NULL_SQL.format(column="age", table='"PUBLIC"."USERS"')
18
+ assert "COUNT(*) FILTER" in sql.upper()
19
+ assert '"age" IS NULL' in sql
20
+ assert '"PUBLIC"."USERS"' in sql
21
+
22
+
23
+ def test_regex_uses_snowflake_rlike() -> None:
24
+ """Snowflake regex is RLIKE — not ~ (Postgres) and not REGEXP_MATCHES (DuckDB)."""
25
+ sql = REGEX_SQL.format(column="email", table='"USERS"')
26
+ assert "RLIKE" in sql.upper()
27
+
28
+
29
+ def test_unique_groups_with_having() -> None:
30
+ sql = UNIQUE_SQL.format(column="id", table='"USERS"')
31
+ assert "GROUP BY" in sql.upper()
32
+ assert "HAVING COUNT(*) > 1" in sql.upper()
33
+
34
+
35
+ def test_between_uses_named_params() -> None:
36
+ sql = BETWEEN_SQL.format(column="age", table='"USERS"')
37
+ # Snowflake parameter style is %(name)s (same as psycopg / Postgres)
38
+ assert "%(min)s" in sql
39
+ assert "%(max)s" in sql
40
+
41
+
42
+ def test_in_set_uses_placeholder_list() -> None:
43
+ """in_set uses {value_list} placeholder filled by the adapter at call time."""
44
+ assert "{value_list}" in IN_SET_SQL
45
+
46
+
47
+ def test_reference_lookup_uses_placeholder_list() -> None:
48
+ assert "{value_list}" in REFERENCE_LOOKUP_SQL
49
+
50
+
51
+ def test_row_count_is_simple_select_count() -> None:
52
+ sql = ROW_COUNT_SQL.format(table='"USERS"')
53
+ assert "COUNT(*)" in sql.upper()
54
+
55
+
56
+ def test_not_negative_filters_negative_values() -> None:
57
+ sql = NOT_NEGATIVE_SQL.format(column="amount", table='"USERS"')
58
+ assert '"amount" < 0' in sql
59
+
60
+
61
+ def test_table_exists_uses_information_schema() -> None:
62
+ assert "%(schema)s" in TABLE_EXISTS_SQL
63
+ assert "%(table)s" in TABLE_EXISTS_SQL
64
+ assert "INFORMATION_SCHEMA.TABLES" in TABLE_EXISTS_SQL.upper()