sqlrules-mysql 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,46 @@
1
+ from __future__ import annotations
2
+
3
+ from sqlrules.plugins import PLUGIN_API_VERSION
4
+ from sqlrules.translators import TranslatorRegistry
5
+ from sqlrules_mysql.fulltext import translate_fulltext_match
6
+ from sqlrules_mysql.json import translate_json_contains, translate_json_has_key
7
+ from sqlrules_mysql.pattern import translate_pattern
8
+ from sqlrules_mysql.type_check import translate_type_check
9
+
10
+ __version__ = "1.0.0"
11
+
12
+
13
+ class MysqlPlugin:
14
+ """Register MySQL / MariaDB constraint translators."""
15
+
16
+ name = "mysql"
17
+ api_version = PLUGIN_API_VERSION
18
+
19
+ def register(self, registry: TranslatorRegistry) -> None:
20
+ registry.register_constraint(
21
+ "pattern",
22
+ translate_pattern,
23
+ on_conflict="replace",
24
+ )
25
+ registry.register_constraint(
26
+ "type_check",
27
+ translate_type_check,
28
+ on_conflict="replace",
29
+ )
30
+ for operator, translator in (
31
+ ("json_contains", translate_json_contains),
32
+ ("json_has_key", translate_json_has_key),
33
+ ("fulltext_match", translate_fulltext_match),
34
+ ):
35
+ registry.register_constraint(operator, translator, on_conflict="replace")
36
+
37
+
38
+ __all__ = [
39
+ "MysqlPlugin",
40
+ "__version__",
41
+ "translate_fulltext_match",
42
+ "translate_json_contains",
43
+ "translate_json_has_key",
44
+ "translate_pattern",
45
+ "translate_type_check",
46
+ ]
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, cast
4
+
5
+ from sqlalchemy.sql.elements import ColumnElement
6
+
7
+ from sqlrules.ir import CompilationContext, Constraint
8
+
9
+
10
+ def translate_fulltext_match(
11
+ constraint: Constraint,
12
+ column: ColumnElement[Any],
13
+ context: CompilationContext,
14
+ ) -> ColumnElement[bool]:
15
+ """Translate ``fulltext_match`` to MySQL ``MATCH (...) AGAINST (...)``.
16
+
17
+ Applications remain responsible for having a FULLTEXT index on the
18
+ target column(s).
19
+ """
20
+ return cast(ColumnElement[bool], column.match(constraint.value))
sqlrules_mysql/json.py ADDED
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any, cast
5
+
6
+ from sqlalchemy import func, literal
7
+ from sqlalchemy.sql.elements import ColumnElement
8
+
9
+ from sqlrules.ir import CompilationContext, Constraint
10
+
11
+
12
+ def _json_path_for_key(key: Any) -> str:
13
+ """Build a JSONPath for a single object key (never a full-path escape hatch)."""
14
+ text = str(key)
15
+ escaped = text.replace("\\", "\\\\").replace('"', '\\"')
16
+ return f'$."{escaped}"'
17
+
18
+
19
+ def translate_json_contains(
20
+ constraint: Constraint,
21
+ column: ColumnElement[Any],
22
+ context: CompilationContext,
23
+ ) -> ColumnElement[bool]:
24
+ """Translate ``json_contains`` to MySQL ``JSON_CONTAINS``."""
25
+ payload = constraint.value
26
+ if not isinstance(payload, str):
27
+ payload = json.dumps(payload, separators=(",", ":"))
28
+ return cast(ColumnElement[bool], func.json_contains(column, payload) == 1)
29
+
30
+
31
+ def translate_json_has_key(
32
+ constraint: Constraint,
33
+ column: ColumnElement[Any],
34
+ context: CompilationContext,
35
+ ) -> ColumnElement[bool]:
36
+ """Translate ``json_has_key`` to MySQL ``JSON_CONTAINS_PATH``."""
37
+ path = _json_path_for_key(constraint.value)
38
+ return cast(
39
+ ColumnElement[bool],
40
+ func.json_contains_path(column, literal("one"), path) == 1,
41
+ )
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, cast
4
+
5
+ from sqlalchemy.sql.elements import ColumnElement
6
+
7
+ from sqlrules.constraints import pattern_text
8
+ from sqlrules.ir import CompilationContext, Constraint
9
+
10
+
11
+ def translate_pattern(
12
+ constraint: Constraint,
13
+ column: ColumnElement[Any],
14
+ context: CompilationContext,
15
+ ) -> ColumnElement[bool]:
16
+ """Translate ``pattern`` to MySQL/MariaDB ``REGEXP``.
17
+
18
+ MySQL ``REGEXP`` is case-insensitive for non-binary collations. SQLRules
19
+ follows that dialect behavior rather than inventing ``REGEXP BINARY``.
20
+ """
21
+ pattern, _ignore_case = pattern_text(constraint.value)
22
+ return cast(ColumnElement[bool], column.op("REGEXP")(pattern))
File without changes
@@ -0,0 +1,238 @@
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.sql.elements import ColumnElement
10
+ from sqlalchemy.sql.sqltypes import NullType
11
+ from sqlalchemy.types import TypeEngine
12
+
13
+ from sqlrules.constraints import type_spec
14
+ from sqlrules.errors import UnsupportedConstraintError
15
+ from sqlrules.ir import CompilationContext, Constraint, TypeSpec
16
+
17
+ _INT_TEXT = r"^[+-]?(0|[1-9][0-9]*)$"
18
+ _FLOAT_TEXT = r"^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$"
19
+ _DATE_TEXT = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
20
+ _DATETIME_TEXT = (
21
+ r"^[0-9]{4}-[0-9]{2}-[0-9]{2}[ T][0-9]{2}:[0-9]{2}:[0-9]{2}"
22
+ r"(\.[0-9]+)?([+-][0-9]{2}:?[0-9]{2}|Z)?$"
23
+ )
24
+ _TIME_TEXT = r"^[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?$"
25
+ _UUID_TEXT = (
26
+ r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
27
+ r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
28
+ )
29
+
30
+
31
+ def _is_type(column: ColumnElement[Any], *bases: type[TypeEngine[Any]]) -> bool:
32
+ col_type = column.type
33
+ if isinstance(col_type, NullType):
34
+ return False
35
+ return isinstance(col_type, bases)
36
+
37
+
38
+ def _regexp(column: ColumnElement[Any], pattern: str) -> ColumnElement[bool]:
39
+ return cast(ColumnElement[bool], column.op("REGEXP")(pattern))
40
+
41
+
42
+ def _wrap_none(
43
+ column: ColumnElement[Any],
44
+ predicate: ColumnElement[bool],
45
+ *,
46
+ allow_none: bool,
47
+ ) -> ColumnElement[bool]:
48
+ if allow_none:
49
+ return cast(ColumnElement[bool], column.is_(None) | predicate)
50
+ return predicate
51
+
52
+
53
+ def _unsupported(field: str, spec: TypeSpec, suggestion: str) -> None:
54
+ raise UnsupportedConstraintError(
55
+ field=field,
56
+ operator="type_check",
57
+ value=spec,
58
+ suggestion=suggestion,
59
+ )
60
+
61
+
62
+ def _predicate_int(
63
+ column: ColumnElement[Any],
64
+ spec: TypeSpec,
65
+ field: str,
66
+ ) -> ColumnElement[bool]:
67
+ if _is_type(column, Integer):
68
+ return cast(ColumnElement[bool], column.isnot(None))
69
+ if spec.strict:
70
+ _unsupported(
71
+ field,
72
+ spec,
73
+ "MySQL strict int type_check requires an Integer column.",
74
+ )
75
+ if _is_type(column, String):
76
+ return _regexp(column, _INT_TEXT)
77
+ if _is_type(column, Float, Numeric):
78
+ return cast(ColumnElement[bool], column == column.cast(Integer).cast(Float))
79
+ _unsupported(
80
+ field,
81
+ spec,
82
+ "MySQL lax int type_check supports Integer, String, Float, or Numeric columns.",
83
+ )
84
+ raise AssertionError("unreachable")
85
+
86
+
87
+ def _predicate_bool(
88
+ column: ColumnElement[Any],
89
+ spec: TypeSpec,
90
+ field: str,
91
+ ) -> ColumnElement[bool]:
92
+ if spec.strict:
93
+ if _is_type(column, Boolean, Integer):
94
+ return cast(ColumnElement[bool], column.in_((True, False, 0, 1)))
95
+ _unsupported(
96
+ field,
97
+ spec,
98
+ "MySQL strict bool type_check requires a Boolean/Integer column.",
99
+ )
100
+ _unsupported(
101
+ field,
102
+ spec,
103
+ "MySQL lax bool type_check is not supported. Use strict=True.",
104
+ )
105
+ raise AssertionError("unreachable")
106
+
107
+
108
+ def _predicate_str(
109
+ column: ColumnElement[Any],
110
+ spec: TypeSpec,
111
+ field: str,
112
+ ) -> ColumnElement[bool]:
113
+ if _is_type(column, String):
114
+ return cast(ColumnElement[bool], column.isnot(None))
115
+ _unsupported(
116
+ field,
117
+ spec,
118
+ "MySQL str type_check requires a String/Text column.",
119
+ )
120
+ raise AssertionError("unreachable")
121
+
122
+
123
+ def _predicate_float(
124
+ column: ColumnElement[Any],
125
+ spec: TypeSpec,
126
+ field: str,
127
+ ) -> ColumnElement[bool]:
128
+ if _is_type(column, Float, Numeric, Integer):
129
+ return cast(ColumnElement[bool], column.isnot(None))
130
+ if spec.strict:
131
+ _unsupported(
132
+ field,
133
+ spec,
134
+ "MySQL strict float/Decimal type_check requires a numeric column.",
135
+ )
136
+ if _is_type(column, String):
137
+ return _regexp(column, _FLOAT_TEXT)
138
+ _unsupported(
139
+ field,
140
+ spec,
141
+ "MySQL float/Decimal type_check supports numeric or String columns.",
142
+ )
143
+ raise AssertionError("unreachable")
144
+
145
+
146
+ def _predicate_temporal(
147
+ column: ColumnElement[Any],
148
+ spec: TypeSpec,
149
+ field: str,
150
+ *,
151
+ sa_types: tuple[type[TypeEngine[Any]], ...],
152
+ text_pattern: str,
153
+ ) -> ColumnElement[bool]:
154
+ if _is_type(column, *sa_types):
155
+ return cast(ColumnElement[bool], column.isnot(None))
156
+ if spec.strict:
157
+ type_name = spec.python_type.__name__
158
+ _unsupported(
159
+ field,
160
+ spec,
161
+ f"MySQL strict {type_name} type_check requires a typed {type_name} column.",
162
+ )
163
+ if _is_type(column, String):
164
+ return _regexp(column, text_pattern)
165
+ type_name = spec.python_type.__name__
166
+ _unsupported(
167
+ field,
168
+ spec,
169
+ f"MySQL {type_name} type_check supports typed {type_name} or String columns.",
170
+ )
171
+ raise AssertionError("unreachable")
172
+
173
+
174
+ def _predicate_uuid(
175
+ column: ColumnElement[Any],
176
+ spec: TypeSpec,
177
+ field: str,
178
+ ) -> ColumnElement[bool]:
179
+ if "uuid" in type(column.type).__name__.lower():
180
+ return cast(ColumnElement[bool], column.isnot(None))
181
+ if spec.strict:
182
+ _unsupported(
183
+ field,
184
+ spec,
185
+ "MySQL strict UUID type_check requires a UUID column.",
186
+ )
187
+ if _is_type(column, String):
188
+ return _regexp(column, _UUID_TEXT)
189
+ _unsupported(
190
+ field,
191
+ spec,
192
+ "MySQL UUID type_check supports UUID or String columns.",
193
+ )
194
+ raise AssertionError("unreachable")
195
+
196
+
197
+ def _build_predicate(
198
+ column: ColumnElement[Any],
199
+ spec: TypeSpec,
200
+ field: str,
201
+ ) -> ColumnElement[bool]:
202
+ python_type = spec.python_type
203
+ if python_type is int:
204
+ return _predicate_int(column, spec, field)
205
+ if python_type is bool:
206
+ return _predicate_bool(column, spec, field)
207
+ if python_type is str:
208
+ return _predicate_str(column, spec, field)
209
+ if python_type in {float, Decimal}:
210
+ return _predicate_float(column, spec, field)
211
+ if python_type is date:
212
+ return _predicate_temporal(column, spec, field, sa_types=(Date,), text_pattern=_DATE_TEXT)
213
+ if python_type is datetime:
214
+ return _predicate_temporal(
215
+ column, spec, field, sa_types=(DateTime,), text_pattern=_DATETIME_TEXT
216
+ )
217
+ if python_type is time:
218
+ return _predicate_temporal(column, spec, field, sa_types=(Time,), text_pattern=_TIME_TEXT)
219
+ if python_type is UUID:
220
+ return _predicate_uuid(column, spec, field)
221
+ _unsupported(
222
+ field,
223
+ spec,
224
+ f"MySQL type_check has no translator for {python_type!r}.",
225
+ )
226
+ raise AssertionError("unreachable")
227
+
228
+
229
+ def translate_type_check(
230
+ constraint: Constraint,
231
+ column: ColumnElement[Any],
232
+ context: CompilationContext,
233
+ ) -> ColumnElement[bool]:
234
+ """Translate ``type_check`` into MySQL shape/type predicates."""
235
+ del context
236
+ spec = type_spec(constraint.value)
237
+ predicate = _build_predicate(column, spec, constraint.field)
238
+ return _wrap_none(column, predicate, allow_none=spec.allow_none)
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlrules-mysql
3
+ Version: 1.0.0
4
+ Summary: MySQL/MariaDB dialect plugin for SQLRules (REGEXP, JSON, full-text).
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: mariadb,mysql,pydantic,sqlalchemy,sqlrules
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-mysql
24
+
25
+ MySQL / MariaDB dialect plugin for [SQLRules](https://github.com/eddiethedean/sqlrules).
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install sqlrules-mysql
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, FullTextMatch, JsonContains
41
+ from sqlrules_mysql import MysqlPlugin
42
+
43
+ class RowFilter(BaseModel):
44
+ name: Annotated[str, Field(pattern=r"^A")]
45
+ meta: Annotated[dict[str, Any], JsonContains({"active": True})]
46
+ body: Annotated[str, FullTextMatch("sqlrules")]
47
+
48
+ compiler = Compiler(plugins=[MysqlPlugin()], dialect="mysql")
49
+ ```
50
+
51
+ ## Operators
52
+
53
+ | IR operator | Notes |
54
+ |---|---|
55
+ | `pattern` | `REGEXP` (case-insensitive under typical collations) |
56
+ | `type_check` | Shape/type predicates from `TypeSpec` (partial matrix) |
57
+ | `json_contains` | `JSON_CONTAINS(column, payload) = 1` |
58
+ | `json_has_key` | `JSON_CONTAINS_PATH(column, 'one', '$.key') = 1` |
59
+ | `fulltext_match` | `MATCH(column) AGAINST (value)` — requires a FULLTEXT index |
60
+
61
+ ## Security note
62
+
63
+ `pattern` / `fulltext_match` values are bound parameters, but evaluation cost
64
+ is engine-dependent. Prefer static/allowlisted patterns and queries from
65
+ untrusted input. See
66
+ [SECURITY](https://sqlrules.readthedocs.io/en/latest/SECURITY.html).
@@ -0,0 +1,10 @@
1
+ sqlrules_mysql/__init__.py,sha256=wp61i0b9xeRI4TDnvhUmrnE5a9ItoFOG3syE5pmz5e8,1395
2
+ sqlrules_mysql/fulltext.py,sha256=fTQWIvoYjbyDr9JeyIkUw_9wJbaJoG97mwEjjZ00euM,570
3
+ sqlrules_mysql/json.py,sha256=QZAJRfs2hE8_Q7-DBIF54j9xnQ4Qn7LKz3Uvpi-bZJs,1269
4
+ sqlrules_mysql/pattern.py,sha256=UspYJFHb7LbGtSAOwMHrF2P1iCImQxj4cKENOtCU_nQ,707
5
+ sqlrules_mysql/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ sqlrules_mysql/type_check.py,sha256=kHS1jwr_xS0nhG7hui8DGYR0JfgZsTHVzt7bTWYMOak,7153
7
+ sqlrules_mysql-1.0.0.dist-info/METADATA,sha256=HGfxqQJJBs0JS_h7oXBdZCoSiJYNqBnpFlrz71qJBWQ,2120
8
+ sqlrules_mysql-1.0.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
9
+ sqlrules_mysql-1.0.0.dist-info/licenses/LICENSE,sha256=cLMlkCH6RhjWAkXBWR7LazV98TOG0WkPtCKB5zqqkAs,1078
10
+ sqlrules_mysql-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.