sqlrules-mssql 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ ]
sqlrules_mssql/json.py ADDED
@@ -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,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,9 @@
1
+ sqlrules_mssql/__init__.py,sha256=vQ2s7iirF9f2ABu0MdxnpsPiKdAaHE82x_LfEHN5TFg,1735
2
+ sqlrules_mssql/json.py,sha256=hf1oSKv2HTJkMT2H3tCYiBlW-AUdNWaj8s-Z_hwonZs,4328
3
+ sqlrules_mssql/length.py,sha256=pHsdRQO_T2bM_zeldbWV4sna3DiwdfBDXMeGbc5elv8,1034
4
+ sqlrules_mssql/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ sqlrules_mssql/type_check.py,sha256=fgae3S5QVfJ0655c7DfkAUQiDriVwmlGXsKb72yt9SU,7191
6
+ sqlrules_mssql-1.0.0.dist-info/METADATA,sha256=04Fyfprle2CLZHSddMDwzAG0NkYLXQvG0qEjLMRGGbY,1871
7
+ sqlrules_mssql-1.0.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
8
+ sqlrules_mssql-1.0.0.dist-info/licenses/LICENSE,sha256=cLMlkCH6RhjWAkXBWR7LazV98TOG0WkPtCKB5zqqkAs,1078
9
+ sqlrules_mssql-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.