sqlrules-mssql 1.0.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.
- sqlrules_mssql-1.0.0/.gitignore +21 -0
- sqlrules_mssql-1.0.0/LICENSE +21 -0
- sqlrules_mssql-1.0.0/PKG-INFO +60 -0
- sqlrules_mssql-1.0.0/README.md +38 -0
- sqlrules_mssql-1.0.0/pyproject.toml +48 -0
- sqlrules_mssql-1.0.0/src/sqlrules_mssql/__init__.py +59 -0
- sqlrules_mssql-1.0.0/src/sqlrules_mssql/json.py +125 -0
- sqlrules_mssql-1.0.0/src/sqlrules_mssql/length.py +31 -0
- sqlrules_mssql-1.0.0/src/sqlrules_mssql/py.typed +0 -0
- sqlrules_mssql-1.0.0/src/sqlrules_mssql/type_check.py +232 -0
- sqlrules_mssql-1.0.0/tests/test_mssql_plugin.py +166 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
.venv/
|
|
2
|
+
venv/
|
|
3
|
+
__pycache__/
|
|
4
|
+
*.py[cod]
|
|
5
|
+
*$py.class
|
|
6
|
+
.pytest_cache/
|
|
7
|
+
.mypy_cache/
|
|
8
|
+
.ruff_cache/
|
|
9
|
+
.coverage
|
|
10
|
+
.coverage.*
|
|
11
|
+
htmlcov/
|
|
12
|
+
dist/
|
|
13
|
+
dist-plugins/
|
|
14
|
+
build/
|
|
15
|
+
*.egg-info/
|
|
16
|
+
.DS_Store
|
|
17
|
+
.idea/
|
|
18
|
+
.vscode/
|
|
19
|
+
*.swp
|
|
20
|
+
*.swo
|
|
21
|
+
docs/_build/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SQLRules Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqlrules-mssql
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: SQL Server dialect plugin for SQLRules (JSON and LEN string ops).
|
|
5
|
+
Project-URL: Homepage, https://github.com/eddiethedean/sqlrules
|
|
6
|
+
Project-URL: Repository, https://github.com/eddiethedean/sqlrules
|
|
7
|
+
Project-URL: Issues, https://github.com/eddiethedean/sqlrules/issues
|
|
8
|
+
Author: SQLRules Contributors
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: mssql,pydantic,sqlalchemy,sqlrules,sqlserver
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: sqlalchemy<3,>=2.0
|
|
18
|
+
Requires-Dist: sqlrules<2,>=1
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# sqlrules-mssql
|
|
24
|
+
|
|
25
|
+
SQL Server dialect plugin for [SQLRules](https://github.com/eddiethedean/sqlrules).
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install sqlrules-mssql
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from typing import Annotated, Any
|
|
37
|
+
|
|
38
|
+
from pydantic import BaseModel, Field
|
|
39
|
+
|
|
40
|
+
from sqlrules import Compiler, JsonContains, JsonHasKey
|
|
41
|
+
from sqlrules_mssql import MssqlPlugin
|
|
42
|
+
|
|
43
|
+
class RowFilter(BaseModel):
|
|
44
|
+
name: Annotated[str, Field(min_length=2, max_length=40)]
|
|
45
|
+
meta: Annotated[dict[str, Any], JsonContains({"active": True}), JsonHasKey("active")]
|
|
46
|
+
|
|
47
|
+
compiler = Compiler(plugins=[MssqlPlugin()], dialect="mssql")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Operators
|
|
51
|
+
|
|
52
|
+
| IR operator | Notes |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `min_length` / `max_length` | `LEN(column)` instead of portable `length()` |
|
|
55
|
+
| `type_check` | Limited shape checks (typed columns; LIKE for some String forms) |
|
|
56
|
+
| `json_contains` | Shallow `JSON_VALUE` / `JSON_QUERY` checks |
|
|
57
|
+
| `json_has_key` | `JSON_VALUE` / `JSON_QUERY` IS NOT NULL |
|
|
58
|
+
|
|
59
|
+
`pattern` is intentionally not registered — prefer a custom translator over
|
|
60
|
+
guessing LIKE semantics.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# sqlrules-mssql
|
|
2
|
+
|
|
3
|
+
SQL Server dialect plugin for [SQLRules](https://github.com/eddiethedean/sqlrules).
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install sqlrules-mssql
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from typing import Annotated, Any
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, Field
|
|
17
|
+
|
|
18
|
+
from sqlrules import Compiler, JsonContains, JsonHasKey
|
|
19
|
+
from sqlrules_mssql import MssqlPlugin
|
|
20
|
+
|
|
21
|
+
class RowFilter(BaseModel):
|
|
22
|
+
name: Annotated[str, Field(min_length=2, max_length=40)]
|
|
23
|
+
meta: Annotated[dict[str, Any], JsonContains({"active": True}), JsonHasKey("active")]
|
|
24
|
+
|
|
25
|
+
compiler = Compiler(plugins=[MssqlPlugin()], dialect="mssql")
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Operators
|
|
29
|
+
|
|
30
|
+
| IR operator | Notes |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `min_length` / `max_length` | `LEN(column)` instead of portable `length()` |
|
|
33
|
+
| `type_check` | Limited shape checks (typed columns; LIKE for some String forms) |
|
|
34
|
+
| `json_contains` | Shallow `JSON_VALUE` / `JSON_QUERY` checks |
|
|
35
|
+
| `json_has_key` | `JSON_VALUE` / `JSON_QUERY` IS NOT NULL |
|
|
36
|
+
|
|
37
|
+
`pattern` is intentionally not registered — prefer a custom translator over
|
|
38
|
+
guessing LIKE semantics.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sqlrules-mssql"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "SQL Server dialect plugin for SQLRules (JSON and LEN string ops)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "SQLRules Contributors" }]
|
|
13
|
+
keywords = ["sqlrules", "mssql", "sqlserver", "pydantic", "sqlalchemy"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 5 - Production/Stable",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"sqlrules>=1,<2",
|
|
22
|
+
"sqlalchemy>=2.0,<3",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/eddiethedean/sqlrules"
|
|
27
|
+
Repository = "https://github.com/eddiethedean/sqlrules"
|
|
28
|
+
Issues = "https://github.com/eddiethedean/sqlrules/issues"
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
dev = [
|
|
32
|
+
"pytest>=8.0",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.sdist]
|
|
36
|
+
include = [
|
|
37
|
+
"/src",
|
|
38
|
+
"/tests",
|
|
39
|
+
"/README.md",
|
|
40
|
+
"/LICENSE",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.wheel]
|
|
44
|
+
packages = ["src/sqlrules_mssql"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from sqlrules.plugins import PLUGIN_API_VERSION
|
|
4
|
+
from sqlrules.translators import TranslatorRegistry
|
|
5
|
+
from sqlrules_mssql.json import translate_json_contains, translate_json_has_key
|
|
6
|
+
from sqlrules_mssql.length import translate_max_length, translate_min_length
|
|
7
|
+
from sqlrules_mssql.type_check import translate_type_check
|
|
8
|
+
|
|
9
|
+
__version__ = "1.0.0"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MssqlPlugin:
|
|
13
|
+
"""Register SQL Server constraint translators.
|
|
14
|
+
|
|
15
|
+
Does not register ``pattern`` — SQL Server has no portable regex operator
|
|
16
|
+
that SQLRules can emit deterministically. Provide a custom translator if
|
|
17
|
+
needed. ``type_check`` is registered with a limited approximation matrix.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
name = "mssql"
|
|
21
|
+
api_version = PLUGIN_API_VERSION
|
|
22
|
+
|
|
23
|
+
def register(self, registry: TranslatorRegistry) -> None:
|
|
24
|
+
registry.register_constraint(
|
|
25
|
+
"min_length",
|
|
26
|
+
translate_min_length,
|
|
27
|
+
on_conflict="replace",
|
|
28
|
+
)
|
|
29
|
+
registry.register_constraint(
|
|
30
|
+
"max_length",
|
|
31
|
+
translate_max_length,
|
|
32
|
+
on_conflict="replace",
|
|
33
|
+
)
|
|
34
|
+
registry.register_constraint(
|
|
35
|
+
"type_check",
|
|
36
|
+
translate_type_check,
|
|
37
|
+
on_conflict="replace",
|
|
38
|
+
)
|
|
39
|
+
registry.register_constraint(
|
|
40
|
+
"json_contains",
|
|
41
|
+
translate_json_contains,
|
|
42
|
+
on_conflict="replace",
|
|
43
|
+
)
|
|
44
|
+
registry.register_constraint(
|
|
45
|
+
"json_has_key",
|
|
46
|
+
translate_json_has_key,
|
|
47
|
+
on_conflict="replace",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"MssqlPlugin",
|
|
53
|
+
"__version__",
|
|
54
|
+
"translate_json_contains",
|
|
55
|
+
"translate_json_has_key",
|
|
56
|
+
"translate_max_length",
|
|
57
|
+
"translate_min_length",
|
|
58
|
+
"translate_type_check",
|
|
59
|
+
]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any, cast
|
|
5
|
+
|
|
6
|
+
from sqlalchemy import String, exists, func, literal, select, type_coerce
|
|
7
|
+
from sqlalchemy import cast as sa_cast
|
|
8
|
+
from sqlalchemy import column as sa_column
|
|
9
|
+
from sqlalchemy.sql.elements import ColumnElement
|
|
10
|
+
|
|
11
|
+
from sqlrules.ir import CompilationContext, Constraint
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _json_path_for_key(key: Any) -> str:
|
|
15
|
+
"""Build a JSONPath for a single object key (never a full-path escape hatch)."""
|
|
16
|
+
text = str(key)
|
|
17
|
+
# SQL Server JSON path quotes use doubled double-quotes inside the name.
|
|
18
|
+
escaped = text.replace('"', '""')
|
|
19
|
+
return f'$."{escaped}"'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _compact_dumps(value: Any) -> str:
|
|
23
|
+
return json.dumps(value, separators=(",", ":"))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _openjson_key_exists(
|
|
27
|
+
column: ColumnElement[Any],
|
|
28
|
+
key: str,
|
|
29
|
+
*,
|
|
30
|
+
json_type: str | None = None,
|
|
31
|
+
) -> ColumnElement[bool]:
|
|
32
|
+
"""True when OPENJSON lists ``key`` (optionally with a specific JSON type)."""
|
|
33
|
+
oj = (
|
|
34
|
+
func.openjson(column)
|
|
35
|
+
.table_valued(
|
|
36
|
+
sa_column("key", String),
|
|
37
|
+
sa_column("value", String),
|
|
38
|
+
sa_column("type", String),
|
|
39
|
+
)
|
|
40
|
+
.render_derived(name="oj", with_types=True)
|
|
41
|
+
.alias("oj")
|
|
42
|
+
)
|
|
43
|
+
predicate = oj.c.key == key
|
|
44
|
+
if json_type is not None:
|
|
45
|
+
predicate = predicate & (oj.c.type == json_type)
|
|
46
|
+
return cast(ColumnElement[bool], exists(select(1).select_from(oj).where(predicate)))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def translate_json_contains(
|
|
50
|
+
constraint: Constraint,
|
|
51
|
+
column: ColumnElement[Any],
|
|
52
|
+
context: CompilationContext,
|
|
53
|
+
) -> ColumnElement[bool]:
|
|
54
|
+
"""Translate ``json_contains`` using SQL Server JSON functions.
|
|
55
|
+
|
|
56
|
+
Object payloads use shallow key checks via ``JSON_VALUE`` /
|
|
57
|
+
``JSON_QUERY`` / ``OPENJSON``. Nested deep-merge containment is not
|
|
58
|
+
emulated.
|
|
59
|
+
"""
|
|
60
|
+
value = constraint.value
|
|
61
|
+
if isinstance(value, dict):
|
|
62
|
+
if not value:
|
|
63
|
+
# Align with PostgreSQL ``@> '{}'``: require a non-NULL JSON object.
|
|
64
|
+
return cast(
|
|
65
|
+
ColumnElement[bool],
|
|
66
|
+
column.is_not(None)
|
|
67
|
+
& (func.isjson(column) == 1)
|
|
68
|
+
& func.json_query(column, "$").is_not(None),
|
|
69
|
+
)
|
|
70
|
+
parts: list[ColumnElement[bool]] = []
|
|
71
|
+
for key, expected in value.items():
|
|
72
|
+
path = _json_path_for_key(key)
|
|
73
|
+
key_text = str(key)
|
|
74
|
+
if expected is None:
|
|
75
|
+
parts.append(_openjson_key_exists(column, key_text, json_type="null"))
|
|
76
|
+
elif isinstance(expected, (dict, list)):
|
|
77
|
+
compact = _compact_dumps(expected)
|
|
78
|
+
parts.append(
|
|
79
|
+
cast(
|
|
80
|
+
ColumnElement[bool],
|
|
81
|
+
func.json_query(column, path)
|
|
82
|
+
== func.json_query(sa_cast(literal(compact), String), "$"),
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
elif isinstance(expected, bool):
|
|
86
|
+
expected_text = "true" if expected else "false"
|
|
87
|
+
parts.append(
|
|
88
|
+
cast(
|
|
89
|
+
ColumnElement[bool],
|
|
90
|
+
func.json_value(column, path) == literal(expected_text),
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
elif isinstance(expected, str):
|
|
94
|
+
parts.append(
|
|
95
|
+
cast(
|
|
96
|
+
ColumnElement[bool],
|
|
97
|
+
func.json_value(column, path) == literal(expected),
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
else:
|
|
101
|
+
parts.append(
|
|
102
|
+
cast(
|
|
103
|
+
ColumnElement[bool],
|
|
104
|
+
func.json_value(column, path) == literal(str(expected)),
|
|
105
|
+
)
|
|
106
|
+
)
|
|
107
|
+
expression = parts[0]
|
|
108
|
+
for part in parts[1:]:
|
|
109
|
+
expression = expression & part
|
|
110
|
+
return cast(ColumnElement[bool], expression)
|
|
111
|
+
|
|
112
|
+
compact = _compact_dumps(value)
|
|
113
|
+
return cast(
|
|
114
|
+
ColumnElement[bool],
|
|
115
|
+
type_coerce(column, String) == func.json_query(sa_cast(literal(compact), String), "$"),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def translate_json_has_key(
|
|
120
|
+
constraint: Constraint,
|
|
121
|
+
column: ColumnElement[Any],
|
|
122
|
+
context: CompilationContext,
|
|
123
|
+
) -> ColumnElement[bool]:
|
|
124
|
+
"""Translate ``json_has_key`` via ``OPENJSON`` key presence (includes JSON null)."""
|
|
125
|
+
return _openjson_key_exists(column, str(constraint.value))
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, cast
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import func, literal
|
|
6
|
+
from sqlalchemy.sql.elements import ColumnElement
|
|
7
|
+
|
|
8
|
+
from sqlrules.ir import CompilationContext, Constraint
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _char_length(column: ColumnElement[Any]) -> ColumnElement[Any]:
|
|
12
|
+
"""Character length including trailing spaces (``LEN`` alone strips them)."""
|
|
13
|
+
return func.len(column.concat(literal("."))) - 1
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def translate_min_length(
|
|
17
|
+
constraint: Constraint,
|
|
18
|
+
column: ColumnElement[Any],
|
|
19
|
+
context: CompilationContext,
|
|
20
|
+
) -> ColumnElement[bool]:
|
|
21
|
+
"""Override portable ``length`` with trailing-space-aware SQL Server length."""
|
|
22
|
+
return cast(ColumnElement[bool], _char_length(column) >= constraint.value)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def translate_max_length(
|
|
26
|
+
constraint: Constraint,
|
|
27
|
+
column: ColumnElement[Any],
|
|
28
|
+
context: CompilationContext,
|
|
29
|
+
) -> ColumnElement[bool]:
|
|
30
|
+
"""Override portable ``length`` with trailing-space-aware SQL Server length."""
|
|
31
|
+
return cast(ColumnElement[bool], _char_length(column) <= constraint.value)
|
|
File without changes
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import date, datetime, time
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import Boolean, Date, DateTime, Float, Integer, Numeric, String, Time
|
|
9
|
+
from sqlalchemy import cast as sa_cast
|
|
10
|
+
from sqlalchemy.sql.elements import ColumnElement
|
|
11
|
+
from sqlalchemy.sql.sqltypes import NullType
|
|
12
|
+
from sqlalchemy.types import TypeEngine
|
|
13
|
+
|
|
14
|
+
from sqlrules.constraints import type_spec
|
|
15
|
+
from sqlrules.errors import UnsupportedConstraintError
|
|
16
|
+
from sqlrules.ir import CompilationContext, Constraint, TypeSpec
|
|
17
|
+
|
|
18
|
+
_UUID_LIKE = (
|
|
19
|
+
"[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]"
|
|
20
|
+
"[0-9A-Fa-f][0-9A-Fa-f]-"
|
|
21
|
+
"[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]-"
|
|
22
|
+
"[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]-"
|
|
23
|
+
"[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]-"
|
|
24
|
+
"[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]"
|
|
25
|
+
"[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]"
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _is_type(column: ColumnElement[Any], *bases: type[TypeEngine[Any]]) -> bool:
|
|
30
|
+
col_type = column.type
|
|
31
|
+
if isinstance(col_type, NullType):
|
|
32
|
+
return False
|
|
33
|
+
return isinstance(col_type, bases)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _wrap_none(
|
|
37
|
+
column: ColumnElement[Any],
|
|
38
|
+
predicate: ColumnElement[bool],
|
|
39
|
+
*,
|
|
40
|
+
allow_none: bool,
|
|
41
|
+
) -> ColumnElement[bool]:
|
|
42
|
+
if allow_none:
|
|
43
|
+
return cast(ColumnElement[bool], column.is_(None) | predicate)
|
|
44
|
+
return predicate
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _unsupported(field: str, spec: TypeSpec, suggestion: str) -> None:
|
|
48
|
+
raise UnsupportedConstraintError(
|
|
49
|
+
field=field,
|
|
50
|
+
operator="type_check",
|
|
51
|
+
value=spec,
|
|
52
|
+
suggestion=suggestion,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _predicate_int(
|
|
57
|
+
column: ColumnElement[Any],
|
|
58
|
+
spec: TypeSpec,
|
|
59
|
+
field: str,
|
|
60
|
+
) -> ColumnElement[bool]:
|
|
61
|
+
if _is_type(column, Integer):
|
|
62
|
+
return cast(ColumnElement[bool], column.isnot(None))
|
|
63
|
+
if spec.strict:
|
|
64
|
+
_unsupported(
|
|
65
|
+
field,
|
|
66
|
+
spec,
|
|
67
|
+
"SQL Server strict int type_check requires an Integer column.",
|
|
68
|
+
)
|
|
69
|
+
if _is_type(column, String):
|
|
70
|
+
unsigned = column.like("[0-9]%") & ~column.like("%[^0-9]%")
|
|
71
|
+
signed = column.like("[-+][0-9]%") & ~column.like("[-+]%[^0-9]%")
|
|
72
|
+
return cast(ColumnElement[bool], unsigned | signed)
|
|
73
|
+
if _is_type(column, Float, Numeric):
|
|
74
|
+
return cast(
|
|
75
|
+
ColumnElement[bool],
|
|
76
|
+
column == sa_cast(sa_cast(column, Integer), Float),
|
|
77
|
+
)
|
|
78
|
+
_unsupported(
|
|
79
|
+
field,
|
|
80
|
+
spec,
|
|
81
|
+
"SQL Server lax int type_check supports Integer, String, Float, or Numeric columns.",
|
|
82
|
+
)
|
|
83
|
+
raise AssertionError("unreachable")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _predicate_bool(
|
|
87
|
+
column: ColumnElement[Any],
|
|
88
|
+
spec: TypeSpec,
|
|
89
|
+
field: str,
|
|
90
|
+
) -> ColumnElement[bool]:
|
|
91
|
+
if spec.strict:
|
|
92
|
+
if _is_type(column, Boolean, Integer):
|
|
93
|
+
return cast(ColumnElement[bool], column.in_((True, False, 0, 1)))
|
|
94
|
+
_unsupported(
|
|
95
|
+
field,
|
|
96
|
+
spec,
|
|
97
|
+
"SQL Server strict bool type_check requires a Boolean/Integer column.",
|
|
98
|
+
)
|
|
99
|
+
_unsupported(
|
|
100
|
+
field,
|
|
101
|
+
spec,
|
|
102
|
+
"SQL Server lax bool type_check is not supported. Use strict=True.",
|
|
103
|
+
)
|
|
104
|
+
raise AssertionError("unreachable")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _predicate_str(
|
|
108
|
+
column: ColumnElement[Any],
|
|
109
|
+
spec: TypeSpec,
|
|
110
|
+
field: str,
|
|
111
|
+
) -> ColumnElement[bool]:
|
|
112
|
+
if _is_type(column, String):
|
|
113
|
+
return cast(ColumnElement[bool], column.isnot(None))
|
|
114
|
+
_unsupported(
|
|
115
|
+
field,
|
|
116
|
+
spec,
|
|
117
|
+
"SQL Server str type_check requires a String/Text column.",
|
|
118
|
+
)
|
|
119
|
+
raise AssertionError("unreachable")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _predicate_float(
|
|
123
|
+
column: ColumnElement[Any],
|
|
124
|
+
spec: TypeSpec,
|
|
125
|
+
field: str,
|
|
126
|
+
) -> ColumnElement[bool]:
|
|
127
|
+
if _is_type(column, Float, Numeric, Integer):
|
|
128
|
+
return cast(ColumnElement[bool], column.isnot(None))
|
|
129
|
+
if spec.strict:
|
|
130
|
+
_unsupported(
|
|
131
|
+
field,
|
|
132
|
+
spec,
|
|
133
|
+
"SQL Server strict float/Decimal type_check requires a numeric column.",
|
|
134
|
+
)
|
|
135
|
+
if _is_type(column, String):
|
|
136
|
+
_unsupported(
|
|
137
|
+
field,
|
|
138
|
+
spec,
|
|
139
|
+
"SQL Server lax float/Decimal type_check on String columns is not "
|
|
140
|
+
"supported (no portable numeric shape check). Use a numeric column "
|
|
141
|
+
"or strict=True with Float/Numeric/Integer.",
|
|
142
|
+
)
|
|
143
|
+
_unsupported(
|
|
144
|
+
field,
|
|
145
|
+
spec,
|
|
146
|
+
"SQL Server float/Decimal type_check supports Float, Numeric, or Integer columns.",
|
|
147
|
+
)
|
|
148
|
+
raise AssertionError("unreachable")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _predicate_temporal(
|
|
152
|
+
column: ColumnElement[Any],
|
|
153
|
+
spec: TypeSpec,
|
|
154
|
+
field: str,
|
|
155
|
+
*,
|
|
156
|
+
sa_types: tuple[type[TypeEngine[Any]], ...],
|
|
157
|
+
) -> ColumnElement[bool]:
|
|
158
|
+
if _is_type(column, *sa_types):
|
|
159
|
+
return cast(ColumnElement[bool], column.isnot(None))
|
|
160
|
+
type_name = spec.python_type.__name__
|
|
161
|
+
_unsupported(
|
|
162
|
+
field,
|
|
163
|
+
spec,
|
|
164
|
+
f"SQL Server {type_name} type_check requires a typed {type_name} column "
|
|
165
|
+
"(string date parsing is not emitted without a portable regex).",
|
|
166
|
+
)
|
|
167
|
+
raise AssertionError("unreachable")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _predicate_uuid(
|
|
171
|
+
column: ColumnElement[Any],
|
|
172
|
+
spec: TypeSpec,
|
|
173
|
+
field: str,
|
|
174
|
+
) -> ColumnElement[bool]:
|
|
175
|
+
if "uuid" in type(column.type).__name__.lower():
|
|
176
|
+
return cast(ColumnElement[bool], column.isnot(None))
|
|
177
|
+
if spec.strict:
|
|
178
|
+
_unsupported(
|
|
179
|
+
field,
|
|
180
|
+
spec,
|
|
181
|
+
"SQL Server strict UUID type_check requires a UUID column.",
|
|
182
|
+
)
|
|
183
|
+
if _is_type(column, String):
|
|
184
|
+
return cast(ColumnElement[bool], column.like(_UUID_LIKE))
|
|
185
|
+
_unsupported(
|
|
186
|
+
field,
|
|
187
|
+
spec,
|
|
188
|
+
"SQL Server UUID type_check supports UUID or String columns.",
|
|
189
|
+
)
|
|
190
|
+
raise AssertionError("unreachable")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _build_predicate(
|
|
194
|
+
column: ColumnElement[Any],
|
|
195
|
+
spec: TypeSpec,
|
|
196
|
+
field: str,
|
|
197
|
+
) -> ColumnElement[bool]:
|
|
198
|
+
python_type = spec.python_type
|
|
199
|
+
if python_type is int:
|
|
200
|
+
return _predicate_int(column, spec, field)
|
|
201
|
+
if python_type is bool:
|
|
202
|
+
return _predicate_bool(column, spec, field)
|
|
203
|
+
if python_type is str:
|
|
204
|
+
return _predicate_str(column, spec, field)
|
|
205
|
+
if python_type in {float, Decimal}:
|
|
206
|
+
return _predicate_float(column, spec, field)
|
|
207
|
+
if python_type is date:
|
|
208
|
+
return _predicate_temporal(column, spec, field, sa_types=(Date,))
|
|
209
|
+
if python_type is datetime:
|
|
210
|
+
return _predicate_temporal(column, spec, field, sa_types=(DateTime,))
|
|
211
|
+
if python_type is time:
|
|
212
|
+
return _predicate_temporal(column, spec, field, sa_types=(Time,))
|
|
213
|
+
if python_type is UUID:
|
|
214
|
+
return _predicate_uuid(column, spec, field)
|
|
215
|
+
_unsupported(
|
|
216
|
+
field,
|
|
217
|
+
spec,
|
|
218
|
+
f"SQL Server type_check has no translator for {python_type!r}.",
|
|
219
|
+
)
|
|
220
|
+
raise AssertionError("unreachable")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def translate_type_check(
|
|
224
|
+
constraint: Constraint,
|
|
225
|
+
column: ColumnElement[Any],
|
|
226
|
+
context: CompilationContext,
|
|
227
|
+
) -> ColumnElement[bool]:
|
|
228
|
+
"""Translate ``type_check`` into SQL Server shape/type predicates."""
|
|
229
|
+
del context
|
|
230
|
+
spec = type_spec(constraint.value)
|
|
231
|
+
predicate = _build_predicate(column, spec, constraint.field)
|
|
232
|
+
return _wrap_none(column, predicate, allow_none=spec.allow_none)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Annotated, Any
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
from sqlalchemy import Column, MetaData, String, Table, Text
|
|
8
|
+
from sqlalchemy.dialects import mssql
|
|
9
|
+
from sqlrules_mssql import MssqlPlugin, __version__
|
|
10
|
+
|
|
11
|
+
from sqlrules import Compiler, JsonContains, JsonHasKey, UnsupportedConstraintError
|
|
12
|
+
from sqlrules.conformance import assert_builtins_preserved, assert_plugin_api_compatible
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_version() -> None:
|
|
16
|
+
assert __version__ == "1.0.0"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_plugin_api() -> None:
|
|
20
|
+
plugin = MssqlPlugin()
|
|
21
|
+
assert_plugin_api_compatible(plugin)
|
|
22
|
+
assert_builtins_preserved(plugin, on_conflict="replace")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_length_uses_trailing_space_aware_len() -> None:
|
|
26
|
+
class Filter(BaseModel):
|
|
27
|
+
name: Annotated[str, Field(min_length=2, max_length=10)]
|
|
28
|
+
|
|
29
|
+
table = Table("items", MetaData(), Column("name", String))
|
|
30
|
+
rules = Compiler(
|
|
31
|
+
plugins=[MssqlPlugin()],
|
|
32
|
+
dialect="mssql",
|
|
33
|
+
cache=False,
|
|
34
|
+
).compile(Filter, table)
|
|
35
|
+
dialect = mssql.dialect()
|
|
36
|
+
min_sql = str(rules["name"][0].compile(dialect=dialect)).lower()
|
|
37
|
+
max_sql = str(rules["name"][1].compile(dialect=dialect)).lower()
|
|
38
|
+
assert "len(" in min_sql and ">=" in min_sql
|
|
39
|
+
assert "len(" in max_sql and "<=" in max_sql
|
|
40
|
+
assert "||" in min_sql or "concat" in min_sql or "+" in min_sql
|
|
41
|
+
assert "length(" not in min_sql
|
|
42
|
+
assert "length(" not in max_sql
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_json_operators_compile() -> None:
|
|
46
|
+
class Filter(BaseModel):
|
|
47
|
+
meta: Annotated[dict[str, Any], JsonContains({"active": True}), JsonHasKey("active")]
|
|
48
|
+
|
|
49
|
+
table = Table("items", MetaData(), Column("meta", Text))
|
|
50
|
+
rules = Compiler(
|
|
51
|
+
plugins=[MssqlPlugin()],
|
|
52
|
+
dialect="mssql",
|
|
53
|
+
cache=False,
|
|
54
|
+
).compile(Filter, table)
|
|
55
|
+
assert len(rules["meta"]) == 2
|
|
56
|
+
dialect = mssql.dialect()
|
|
57
|
+
contains_sql = str(rules["meta"][0].compile(dialect=dialect)).lower()
|
|
58
|
+
has_key_sql = str(rules["meta"][1].compile(dialect=dialect)).lower()
|
|
59
|
+
assert "json_value" in contains_sql
|
|
60
|
+
assert "openjson" in has_key_sql
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_json_contains_none_uses_openjson_null_type() -> None:
|
|
64
|
+
class Filter(BaseModel):
|
|
65
|
+
meta: Annotated[dict[str, Any], JsonContains({"a": None})]
|
|
66
|
+
|
|
67
|
+
table = Table("items", MetaData(), Column("meta", Text))
|
|
68
|
+
rules = Compiler(
|
|
69
|
+
plugins=[MssqlPlugin()],
|
|
70
|
+
dialect="mssql",
|
|
71
|
+
cache=False,
|
|
72
|
+
).compile(Filter, table)
|
|
73
|
+
compiled = str(
|
|
74
|
+
rules["meta"][0].compile(
|
|
75
|
+
dialect=mssql.dialect(),
|
|
76
|
+
compile_kwargs={"literal_binds": True},
|
|
77
|
+
)
|
|
78
|
+
).lower()
|
|
79
|
+
assert "openjson" in compiled
|
|
80
|
+
assert "null" in compiled
|
|
81
|
+
assert "'none'" not in compiled
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_json_contains_nested_uses_compact_json_query() -> None:
|
|
85
|
+
class Filter(BaseModel):
|
|
86
|
+
meta: Annotated[dict[str, Any], JsonContains({"nested": {"x": 1}})]
|
|
87
|
+
|
|
88
|
+
table = Table("items", MetaData(), Column("meta", Text))
|
|
89
|
+
rules = Compiler(
|
|
90
|
+
plugins=[MssqlPlugin()],
|
|
91
|
+
dialect="mssql",
|
|
92
|
+
cache=False,
|
|
93
|
+
).compile(Filter, table)
|
|
94
|
+
compiled = str(
|
|
95
|
+
rules["meta"][0].compile(
|
|
96
|
+
dialect=mssql.dialect(),
|
|
97
|
+
compile_kwargs={"literal_binds": True},
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
assert '{"x":1}' in compiled
|
|
101
|
+
assert '{"x": 1}' not in compiled
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_pattern_remains_unsupported() -> None:
|
|
105
|
+
class Filter(BaseModel):
|
|
106
|
+
name: Annotated[str, Field(pattern=r"^A")]
|
|
107
|
+
|
|
108
|
+
table = Table("items", MetaData(), Column("name", String))
|
|
109
|
+
with pytest.raises(UnsupportedConstraintError, match="pattern"):
|
|
110
|
+
Compiler(
|
|
111
|
+
plugins=[MssqlPlugin()],
|
|
112
|
+
dialect="mssql",
|
|
113
|
+
cache=False,
|
|
114
|
+
).compile(Filter, table)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_empty_json_contains_requires_object() -> None:
|
|
118
|
+
class Filter(BaseModel):
|
|
119
|
+
meta: Annotated[dict[str, Any], JsonContains({})]
|
|
120
|
+
|
|
121
|
+
table = Table("items", MetaData(), Column("meta", Text))
|
|
122
|
+
rules = Compiler(
|
|
123
|
+
plugins=[MssqlPlugin()],
|
|
124
|
+
dialect="mssql",
|
|
125
|
+
cache=False,
|
|
126
|
+
).compile(Filter, table)
|
|
127
|
+
assert len(rules["meta"]) == 1
|
|
128
|
+
compiled = str(
|
|
129
|
+
rules["meta"][0].compile(
|
|
130
|
+
dialect=mssql.dialect(),
|
|
131
|
+
compile_kwargs={"literal_binds": True},
|
|
132
|
+
)
|
|
133
|
+
).lower()
|
|
134
|
+
assert "isjson" in compiled
|
|
135
|
+
assert "json_query" in compiled
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_type_check_lax_float_string_unsupported() -> None:
|
|
139
|
+
class Filter(BaseModel):
|
|
140
|
+
score: float
|
|
141
|
+
|
|
142
|
+
table = Table("rows", MetaData(), Column("score", String))
|
|
143
|
+
with pytest.raises(UnsupportedConstraintError, match="float"):
|
|
144
|
+
Compiler(
|
|
145
|
+
plugins=[MssqlPlugin()],
|
|
146
|
+
dialect="mssql",
|
|
147
|
+
emit_type_checks=True,
|
|
148
|
+
cache=False,
|
|
149
|
+
).compile(Filter, table)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_type_check_int_integer_column() -> None:
|
|
153
|
+
from sqlalchemy import Integer
|
|
154
|
+
|
|
155
|
+
class Filter(BaseModel):
|
|
156
|
+
age: int
|
|
157
|
+
|
|
158
|
+
table = Table("users", MetaData(), Column("age", Integer))
|
|
159
|
+
rules = Compiler(
|
|
160
|
+
plugins=[MssqlPlugin()],
|
|
161
|
+
dialect="mssql",
|
|
162
|
+
emit_type_checks=True,
|
|
163
|
+
cache=False,
|
|
164
|
+
).compile(Filter, table)
|
|
165
|
+
compiled = str(rules["age"][0].compile(dialect=mssql.dialect()))
|
|
166
|
+
assert "IS NOT NULL" in compiled.upper()
|