sqlrules-sqlite 1.0.1__tar.gz → 2.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_sqlite-2.0.0/PKG-INFO +84 -0
- sqlrules_sqlite-2.0.0/README.md +62 -0
- {sqlrules_sqlite-1.0.1 → sqlrules_sqlite-2.0.0}/pyproject.toml +3 -3
- sqlrules_sqlite-2.0.0/src/sqlrules_sqlite/__init__.py +95 -0
- sqlrules_sqlite-2.0.0/src/sqlrules_sqlite/json.py +134 -0
- sqlrules_sqlite-2.0.0/src/sqlrules_sqlite/length.py +35 -0
- {sqlrules_sqlite-1.0.1 → sqlrules_sqlite-2.0.0}/src/sqlrules_sqlite/pattern.py +2 -1
- sqlrules_sqlite-2.0.0/src/sqlrules_sqlite/regexp.py +13 -0
- sqlrules_sqlite-2.0.0/src/sqlrules_sqlite/runtime.py +34 -0
- sqlrules_sqlite-2.0.0/tests/test_sqlite_plugin.py +67 -0
- sqlrules_sqlite-1.0.1/PKG-INFO +0 -83
- sqlrules_sqlite-1.0.1/README.md +0 -61
- sqlrules_sqlite-1.0.1/src/sqlrules_sqlite/__init__.py +0 -55
- sqlrules_sqlite-1.0.1/src/sqlrules_sqlite/json.py +0 -94
- sqlrules_sqlite-1.0.1/src/sqlrules_sqlite/regexp.py +0 -30
- sqlrules_sqlite-1.0.1/src/sqlrules_sqlite/type_check.py +0 -213
- sqlrules_sqlite-1.0.1/tests/test_sqlite_plugin.py +0 -314
- {sqlrules_sqlite-1.0.1 → sqlrules_sqlite-2.0.0}/.gitignore +0 -0
- {sqlrules_sqlite-1.0.1 → sqlrules_sqlite-2.0.0}/LICENSE +0 -0
- {sqlrules_sqlite-1.0.1 → sqlrules_sqlite-2.0.0}/src/sqlrules_sqlite/py.typed +0 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sqlrules-sqlite
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: SQLite dialect plugin for SQLRules (REGEXP, Unicode length, and JSON helpers).
|
|
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: pydantic,sqlalchemy,sqlite,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<3,>=2
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# sqlrules-sqlite
|
|
24
|
+
|
|
25
|
+
SQLite backend provider for [SQLRules](https://github.com/eddiethedean/sqlrules).
|
|
26
|
+
The package version follows the core 2.x line.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install "sqlrules>=2,<3" "sqlrules-sqlite>=2,<3"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Use
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from typing import Annotated, Any
|
|
38
|
+
|
|
39
|
+
from pydantic import Field
|
|
40
|
+
from sqlalchemy import Column, JSON, MetaData, String, Table, create_engine, event
|
|
41
|
+
|
|
42
|
+
from sqlrules import Compiler, JsonContains, RuleSchema, where
|
|
43
|
+
from sqlrules_sqlite import SQLitePlugin, register_sqlite_functions
|
|
44
|
+
|
|
45
|
+
rows = Table("rows", MetaData(), Column("name", String), Column("meta", JSON))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class RowRules(RuleSchema):
|
|
49
|
+
name: Annotated[str, Field(pattern=r"^A")]
|
|
50
|
+
meta: Annotated[dict[str, Any], JsonContains({"active": True})]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
engine = create_engine("sqlite:///app.db")
|
|
54
|
+
event.listen(
|
|
55
|
+
engine,
|
|
56
|
+
"connect",
|
|
57
|
+
lambda dbapi_connection, _: register_sqlite_functions(dbapi_connection),
|
|
58
|
+
)
|
|
59
|
+
compiled = Compiler(plugins=[SQLitePlugin()]).compile(RowRules, rows)
|
|
60
|
+
statement = rows.select().where(*where(compiled))
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Capabilities
|
|
64
|
+
|
|
65
|
+
- Runtime `typeof()` checks for SQLite integer, real, and text storage classes
|
|
66
|
+
- Lax text-to-int/float coercion and bool values stored as integer 0 or 1
|
|
67
|
+
- JSON1 helpers that treat malformed documents as non-matches
|
|
68
|
+
- `REGEXP` pattern matching and Unicode-aware string length through
|
|
69
|
+
`register_sqlite_functions()`
|
|
70
|
+
|
|
71
|
+
Strict bool, exact Decimal, and SQLAlchemy-emulated date/time/UUID values need
|
|
72
|
+
explicit storage adapters and raise `CapabilityError`. Text coercion, patterns,
|
|
73
|
+
and string length constraints require the registered SQLRules SQLite functions
|
|
74
|
+
on each connection. `register_regexp()` remains as a backward-compatible alias.
|
|
75
|
+
See the
|
|
76
|
+
[type support matrix](https://sqlrules.readthedocs.io/en/latest/TYPE_SUPPORT.html).
|
|
77
|
+
|
|
78
|
+
## Pattern cost
|
|
79
|
+
|
|
80
|
+
`register_sqlite_functions()` runs Python's `re.search` for each regex row and
|
|
81
|
+
Python's `len()` for each length-checked string row. Untrusted patterns can
|
|
82
|
+
cause CPU denial of service through catastrophic backtracking. Prefer static
|
|
83
|
+
or allowlisted patterns. See the SQLRules
|
|
84
|
+
[security notes](https://sqlrules.readthedocs.io/en/latest/SECURITY.html).
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# sqlrules-sqlite
|
|
2
|
+
|
|
3
|
+
SQLite backend provider for [SQLRules](https://github.com/eddiethedean/sqlrules).
|
|
4
|
+
The package version follows the core 2.x line.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install "sqlrules>=2,<3" "sqlrules-sqlite>=2,<3"
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Use
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from typing import Annotated, Any
|
|
16
|
+
|
|
17
|
+
from pydantic import Field
|
|
18
|
+
from sqlalchemy import Column, JSON, MetaData, String, Table, create_engine, event
|
|
19
|
+
|
|
20
|
+
from sqlrules import Compiler, JsonContains, RuleSchema, where
|
|
21
|
+
from sqlrules_sqlite import SQLitePlugin, register_sqlite_functions
|
|
22
|
+
|
|
23
|
+
rows = Table("rows", MetaData(), Column("name", String), Column("meta", JSON))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RowRules(RuleSchema):
|
|
27
|
+
name: Annotated[str, Field(pattern=r"^A")]
|
|
28
|
+
meta: Annotated[dict[str, Any], JsonContains({"active": True})]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
engine = create_engine("sqlite:///app.db")
|
|
32
|
+
event.listen(
|
|
33
|
+
engine,
|
|
34
|
+
"connect",
|
|
35
|
+
lambda dbapi_connection, _: register_sqlite_functions(dbapi_connection),
|
|
36
|
+
)
|
|
37
|
+
compiled = Compiler(plugins=[SQLitePlugin()]).compile(RowRules, rows)
|
|
38
|
+
statement = rows.select().where(*where(compiled))
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Capabilities
|
|
42
|
+
|
|
43
|
+
- Runtime `typeof()` checks for SQLite integer, real, and text storage classes
|
|
44
|
+
- Lax text-to-int/float coercion and bool values stored as integer 0 or 1
|
|
45
|
+
- JSON1 helpers that treat malformed documents as non-matches
|
|
46
|
+
- `REGEXP` pattern matching and Unicode-aware string length through
|
|
47
|
+
`register_sqlite_functions()`
|
|
48
|
+
|
|
49
|
+
Strict bool, exact Decimal, and SQLAlchemy-emulated date/time/UUID values need
|
|
50
|
+
explicit storage adapters and raise `CapabilityError`. Text coercion, patterns,
|
|
51
|
+
and string length constraints require the registered SQLRules SQLite functions
|
|
52
|
+
on each connection. `register_regexp()` remains as a backward-compatible alias.
|
|
53
|
+
See the
|
|
54
|
+
[type support matrix](https://sqlrules.readthedocs.io/en/latest/TYPE_SUPPORT.html).
|
|
55
|
+
|
|
56
|
+
## Pattern cost
|
|
57
|
+
|
|
58
|
+
`register_sqlite_functions()` runs Python's `re.search` for each regex row and
|
|
59
|
+
Python's `len()` for each length-checked string row. Untrusted patterns can
|
|
60
|
+
cause CPU denial of service through catastrophic backtracking. Prefer static
|
|
61
|
+
or allowlisted patterns. See the SQLRules
|
|
62
|
+
[security notes](https://sqlrules.readthedocs.io/en/latest/SECURITY.html).
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "sqlrules-sqlite"
|
|
7
|
-
version = "
|
|
8
|
-
description = "SQLite dialect plugin for SQLRules (REGEXP
|
|
7
|
+
version = "2.0.0"
|
|
8
|
+
description = "SQLite dialect plugin for SQLRules (REGEXP, Unicode length, and JSON helpers)."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
11
11
|
license = "MIT"
|
|
@@ -18,7 +18,7 @@ classifiers = [
|
|
|
18
18
|
"Typing :: Typed",
|
|
19
19
|
]
|
|
20
20
|
dependencies = [
|
|
21
|
-
"sqlrules>=
|
|
21
|
+
"sqlrules>=2,<3",
|
|
22
22
|
"sqlalchemy>=2.0,<3",
|
|
23
23
|
]
|
|
24
24
|
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from sqlrules.backend import prepare_sqlite_scalar
|
|
7
|
+
from sqlrules.ir import CompilationContext, PreparedValue, RuleField
|
|
8
|
+
from sqlrules.plugins import PLUGIN_API_VERSION
|
|
9
|
+
from sqlrules.translators import TranslatorRegistry
|
|
10
|
+
from sqlrules_sqlite.json import translate_json_contains, translate_json_has_key
|
|
11
|
+
from sqlrules_sqlite.length import translate_max_length, translate_min_length
|
|
12
|
+
from sqlrules_sqlite.pattern import translate_pattern
|
|
13
|
+
from sqlrules_sqlite.regexp import register_regexp
|
|
14
|
+
from sqlrules_sqlite.runtime import register_sqlite_functions
|
|
15
|
+
|
|
16
|
+
__version__ = "2.0.0"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SQLitePlugin:
|
|
20
|
+
"""Register SQLite-specific constraint translators.
|
|
21
|
+
|
|
22
|
+
Pattern and text-coercion expressions emit ``column REGEXP pattern``;
|
|
23
|
+
length constraints use SQLRules' Unicode-aware character counter. Call
|
|
24
|
+
:func:`register_sqlite_functions` on each SQLite connection before
|
|
25
|
+
executing SQL that needs these functions. ``register_regexp`` remains as a
|
|
26
|
+
backward-compatible alias.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
name = "sqlite"
|
|
30
|
+
api_version = PLUGIN_API_VERSION
|
|
31
|
+
|
|
32
|
+
def __init__(self, *, server_version: tuple[int, ...] | None = None) -> None:
|
|
33
|
+
self.server_version = tuple(server_version) if server_version is not None else None
|
|
34
|
+
|
|
35
|
+
def capabilities(self) -> Mapping[str, Any]:
|
|
36
|
+
return {
|
|
37
|
+
"backend": self.name,
|
|
38
|
+
"server_version": self.server_version,
|
|
39
|
+
"native_scalar_types": ("bool", "int", "float", "str"),
|
|
40
|
+
"safe_text_numeric_conversion": True,
|
|
41
|
+
"safe_text_numeric_targets": ("int", "float"),
|
|
42
|
+
"assumptions": (
|
|
43
|
+
"Runtime typeof() storage classes determine bool/int/float/text values.",
|
|
44
|
+
"Register SQLRules SQLite functions on each connection when using text "
|
|
45
|
+
"coercion, patterns, or string length constraints.",
|
|
46
|
+
"Date/time/UUID and exact Decimal checks require "
|
|
47
|
+
"a future explicit storage adapter.",
|
|
48
|
+
),
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
def prepare_value(
|
|
52
|
+
self,
|
|
53
|
+
column: Any,
|
|
54
|
+
field: RuleField,
|
|
55
|
+
context: CompilationContext,
|
|
56
|
+
) -> PreparedValue:
|
|
57
|
+
return prepare_sqlite_scalar(column, field, context)
|
|
58
|
+
|
|
59
|
+
def register(self, registry: TranslatorRegistry) -> None:
|
|
60
|
+
registry.register_constraint(
|
|
61
|
+
"min_length",
|
|
62
|
+
translate_min_length,
|
|
63
|
+
on_conflict="replace",
|
|
64
|
+
)
|
|
65
|
+
registry.register_constraint(
|
|
66
|
+
"max_length",
|
|
67
|
+
translate_max_length,
|
|
68
|
+
on_conflict="replace",
|
|
69
|
+
)
|
|
70
|
+
registry.register_constraint(
|
|
71
|
+
"pattern",
|
|
72
|
+
translate_pattern,
|
|
73
|
+
on_conflict="replace",
|
|
74
|
+
)
|
|
75
|
+
registry.register_constraint(
|
|
76
|
+
"json_contains",
|
|
77
|
+
translate_json_contains,
|
|
78
|
+
on_conflict="replace",
|
|
79
|
+
)
|
|
80
|
+
registry.register_constraint(
|
|
81
|
+
"json_has_key",
|
|
82
|
+
translate_json_has_key,
|
|
83
|
+
on_conflict="replace",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
__all__ = [
|
|
88
|
+
"SQLitePlugin",
|
|
89
|
+
"__version__",
|
|
90
|
+
"register_regexp",
|
|
91
|
+
"register_sqlite_functions",
|
|
92
|
+
"translate_json_contains",
|
|
93
|
+
"translate_json_has_key",
|
|
94
|
+
"translate_pattern",
|
|
95
|
+
]
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any, cast
|
|
5
|
+
|
|
6
|
+
from sqlalchemy import String, and_, case, func, literal, select, type_coerce
|
|
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 _compact_dumps(value: Any) -> str:
|
|
20
|
+
return json.dumps(value, separators=(",", ":"))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _safe_json(column: ColumnElement[Any]) -> ColumnElement[Any]:
|
|
24
|
+
"""Replace malformed documents before any JSON1 function can inspect them."""
|
|
25
|
+
return case(
|
|
26
|
+
(func.json_valid(column), type_coerce(column, String)),
|
|
27
|
+
else_=literal("{}"),
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _json_child_count(
|
|
32
|
+
document: ColumnElement[Any],
|
|
33
|
+
path: str,
|
|
34
|
+
) -> ColumnElement[Any]:
|
|
35
|
+
children = func.json_each(document, path).table_valued("key").alias()
|
|
36
|
+
return select(func.count()).select_from(children).scalar_subquery()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _join_json_path(parent: str, child: str) -> str:
|
|
40
|
+
return f"{parent}{child[1:]}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _json_value_equals(
|
|
44
|
+
document: ColumnElement[Any],
|
|
45
|
+
path: str,
|
|
46
|
+
expected: Any,
|
|
47
|
+
) -> ColumnElement[bool]:
|
|
48
|
+
"""Compare JSON values structurally, independent of object key order."""
|
|
49
|
+
json_type = func.json_type(document, path)
|
|
50
|
+
extracted = func.json_extract(document, path)
|
|
51
|
+
if expected is None:
|
|
52
|
+
return cast(ColumnElement[bool], json_type == "null")
|
|
53
|
+
if isinstance(expected, bool):
|
|
54
|
+
expected_type = "true" if expected else "false"
|
|
55
|
+
return cast(ColumnElement[bool], json_type == expected_type)
|
|
56
|
+
if isinstance(expected, dict):
|
|
57
|
+
parts: list[ColumnElement[bool]] = [
|
|
58
|
+
cast(ColumnElement[bool], json_type == "object"),
|
|
59
|
+
cast(ColumnElement[bool], _json_child_count(document, path) == len(expected)),
|
|
60
|
+
]
|
|
61
|
+
parts.extend(
|
|
62
|
+
_json_value_equals(
|
|
63
|
+
document,
|
|
64
|
+
_join_json_path(path, _json_path_for_key(key)),
|
|
65
|
+
child,
|
|
66
|
+
)
|
|
67
|
+
for key, child in expected.items()
|
|
68
|
+
)
|
|
69
|
+
return cast(ColumnElement[bool], and_(*parts))
|
|
70
|
+
if isinstance(expected, list):
|
|
71
|
+
parts = [
|
|
72
|
+
cast(ColumnElement[bool], json_type == "array"),
|
|
73
|
+
cast(ColumnElement[bool], _json_child_count(document, path) == len(expected)),
|
|
74
|
+
]
|
|
75
|
+
parts.extend(
|
|
76
|
+
_json_value_equals(document, f"{path}[{index}]", child)
|
|
77
|
+
for index, child in enumerate(expected)
|
|
78
|
+
)
|
|
79
|
+
return cast(ColumnElement[bool], and_(*parts))
|
|
80
|
+
if isinstance(expected, (int, float)):
|
|
81
|
+
return cast(
|
|
82
|
+
ColumnElement[bool],
|
|
83
|
+
json_type.in_(("integer", "real")) & (extracted == expected),
|
|
84
|
+
)
|
|
85
|
+
if isinstance(expected, str):
|
|
86
|
+
return cast(ColumnElement[bool], (json_type == "text") & (extracted == expected))
|
|
87
|
+
compact = _compact_dumps(expected)
|
|
88
|
+
return cast(
|
|
89
|
+
ColumnElement[bool],
|
|
90
|
+
func.json(extracted) == func.json(literal(compact)),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def translate_json_contains(
|
|
95
|
+
constraint: Constraint,
|
|
96
|
+
column: ColumnElement[Any],
|
|
97
|
+
context: CompilationContext,
|
|
98
|
+
) -> ColumnElement[bool]:
|
|
99
|
+
"""Translate the supported SQLite JSON containment subset safely."""
|
|
100
|
+
value = constraint.value
|
|
101
|
+
safe_json = _safe_json(column)
|
|
102
|
+
valid_document = func.json_valid(column)
|
|
103
|
+
if isinstance(value, dict):
|
|
104
|
+
if not value:
|
|
105
|
+
return cast(
|
|
106
|
+
ColumnElement[bool],
|
|
107
|
+
column.is_not(None) & valid_document & (func.json_type(safe_json) == "object"),
|
|
108
|
+
)
|
|
109
|
+
parts = [
|
|
110
|
+
_json_value_equals(safe_json, _json_path_for_key(key), expected)
|
|
111
|
+
for key, expected in value.items()
|
|
112
|
+
]
|
|
113
|
+
return cast(
|
|
114
|
+
ColumnElement[bool],
|
|
115
|
+
valid_document & (func.json_type(safe_json) == "object") & and_(*parts),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
return cast(
|
|
119
|
+
ColumnElement[bool],
|
|
120
|
+
valid_document & _json_value_equals(safe_json, "$", value),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def translate_json_has_key(
|
|
125
|
+
constraint: Constraint,
|
|
126
|
+
column: ColumnElement[Any],
|
|
127
|
+
context: CompilationContext,
|
|
128
|
+
) -> ColumnElement[bool]:
|
|
129
|
+
"""Translate ``json_has_key`` without evaluating JSON1 on malformed input."""
|
|
130
|
+
path = _json_path_for_key(constraint.value)
|
|
131
|
+
return cast(
|
|
132
|
+
ColumnElement[bool],
|
|
133
|
+
func.json_valid(column) & func.json_type(_safe_json(column), path).is_not(None),
|
|
134
|
+
)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, cast
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import func
|
|
6
|
+
from sqlalchemy.sql.elements import ColumnElement
|
|
7
|
+
|
|
8
|
+
from sqlrules.ir import CompilationContext, Constraint
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def translate_min_length(
|
|
12
|
+
constraint: Constraint,
|
|
13
|
+
column: ColumnElement[Any],
|
|
14
|
+
context: CompilationContext,
|
|
15
|
+
) -> ColumnElement[bool]:
|
|
16
|
+
"""Use the registered Python-compatible code-point counter."""
|
|
17
|
+
return cast(
|
|
18
|
+
ColumnElement[bool],
|
|
19
|
+
func.sqlrules_char_length(column) >= constraint.value,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def translate_max_length(
|
|
24
|
+
constraint: Constraint,
|
|
25
|
+
column: ColumnElement[Any],
|
|
26
|
+
context: CompilationContext,
|
|
27
|
+
) -> ColumnElement[bool]:
|
|
28
|
+
"""Use the registered Python-compatible code-point counter."""
|
|
29
|
+
return cast(
|
|
30
|
+
ColumnElement[bool],
|
|
31
|
+
func.sqlrules_char_length(column) <= constraint.value,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
__all__ = ["translate_max_length", "translate_min_length"]
|
|
@@ -16,7 +16,8 @@ def translate_pattern(
|
|
|
16
16
|
"""Translate ``pattern`` to SQLite ``column REGEXP pattern``.
|
|
17
17
|
|
|
18
18
|
Case-insensitive patterns are encoded with a ``(?i)`` prefix so
|
|
19
|
-
:func:`sqlrules_sqlite.
|
|
19
|
+
:func:`sqlrules_sqlite.register_sqlite_functions` can apply
|
|
20
|
+
``re.IGNORECASE``.
|
|
20
21
|
Callers must enable REGEXP on the SQLite connection before execution.
|
|
21
22
|
"""
|
|
22
23
|
pattern, ignore_case = pattern_text(constraint.value)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
|
|
5
|
+
from sqlrules_sqlite.runtime import register_sqlite_functions
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def register_regexp(connection: sqlite3.Connection) -> None:
|
|
9
|
+
"""Backward-compatible alias for :func:`register_sqlite_functions`."""
|
|
10
|
+
register_sqlite_functions(connection)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
__all__ = ["register_regexp"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import sqlite3
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _regexp(pattern: str | None, value: str | None) -> bool:
|
|
9
|
+
# SQLite may evaluate a REGEXP branch even when a neighboring typeof()
|
|
10
|
+
# predicate is false. Treat non-text source values as a non-match so
|
|
11
|
+
# mixed-storage tables cannot raise Python TypeError.
|
|
12
|
+
if not isinstance(pattern, str) or not isinstance(value, str):
|
|
13
|
+
return False
|
|
14
|
+
flags = 0
|
|
15
|
+
if pattern.startswith("(?i)"):
|
|
16
|
+
flags |= re.IGNORECASE
|
|
17
|
+
pattern = pattern[4:]
|
|
18
|
+
return re.search(pattern, value, flags) is not None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _char_length(value: Any) -> int | None:
|
|
22
|
+
"""Use Python's Unicode code-point count, including text after U+0000."""
|
|
23
|
+
return len(value) if isinstance(value, str) else None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def register_sqlite_functions(connection: sqlite3.Connection) -> None:
|
|
27
|
+
"""Register SQLRules functions needed by SQLite rules on this connection.
|
|
28
|
+
|
|
29
|
+
SQLite does not provide REGEXP, and its built-in length(TEXT) stops at the
|
|
30
|
+
first U+0000. SQLRules uses these callbacks for regex/text coercion and
|
|
31
|
+
exact Python-compatible string length constraints.
|
|
32
|
+
"""
|
|
33
|
+
connection.create_function("REGEXP", 2, _regexp)
|
|
34
|
+
connection.create_function("sqlrules_char_length", 1, _char_length)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from typing import Annotated, Any
|
|
5
|
+
|
|
6
|
+
from pydantic import Field
|
|
7
|
+
from sqlalchemy import JSON, Column, Integer, MetaData, String, Table, create_engine, select
|
|
8
|
+
from sqlalchemy.dialects.sqlite import dialect
|
|
9
|
+
from sqlrules_sqlite import SQLitePlugin, __version__, register_regexp
|
|
10
|
+
|
|
11
|
+
from sqlrules import Compiler, JsonContains, JsonHasKey, RuleSchema
|
|
12
|
+
from sqlrules.conformance import run_basic_conformance
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_version_and_plugin_conformance() -> None:
|
|
16
|
+
assert __version__ == "2.0.0"
|
|
17
|
+
run_basic_conformance(SQLitePlugin(), operator="pattern")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_pattern_and_json_markers_compile() -> None:
|
|
21
|
+
class Rules(RuleSchema):
|
|
22
|
+
name: Annotated[str, Field(pattern=r"^A")]
|
|
23
|
+
meta: Annotated[dict[str, Any], JsonContains({"active": True}), JsonHasKey("active")]
|
|
24
|
+
|
|
25
|
+
table = Table(
|
|
26
|
+
"rows",
|
|
27
|
+
MetaData(),
|
|
28
|
+
Column("name", String),
|
|
29
|
+
Column("meta", JSON),
|
|
30
|
+
)
|
|
31
|
+
compiled = Compiler(plugins=[SQLitePlugin()]).compile(Rules, table)
|
|
32
|
+
sql = str(compiled.predicate.compile(dialect=dialect()))
|
|
33
|
+
assert "REGEXP" in sql
|
|
34
|
+
assert "json_type" in sql
|
|
35
|
+
assert "json_valid" in sql
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_regexp_handles_text_and_non_text_values() -> None:
|
|
39
|
+
db = sqlite3.connect(":memory:")
|
|
40
|
+
register_regexp(db)
|
|
41
|
+
assert db.execute("SELECT 'Ada' REGEXP '^A'").fetchone() == (1,)
|
|
42
|
+
assert db.execute("SELECT 12 REGEXP '^1'").fetchone() == (0,)
|
|
43
|
+
assert db.execute("SELECT NULL REGEXP '^1'").fetchone() == (0,)
|
|
44
|
+
db.close()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_json_contains_executes_on_sqlite() -> None:
|
|
48
|
+
class Rules(RuleSchema):
|
|
49
|
+
meta: Annotated[dict[str, Any], JsonContains({"active": True})]
|
|
50
|
+
|
|
51
|
+
table = Table(
|
|
52
|
+
"rows",
|
|
53
|
+
MetaData(),
|
|
54
|
+
Column("id", Integer),
|
|
55
|
+
Column("meta", JSON),
|
|
56
|
+
)
|
|
57
|
+
engine = create_engine("sqlite://")
|
|
58
|
+
table.create(engine)
|
|
59
|
+
with engine.begin() as connection:
|
|
60
|
+
connection.exec_driver_sql(
|
|
61
|
+
"INSERT INTO rows (id, meta) VALUES (1, '{\"active\": true}'), "
|
|
62
|
+
"(2, '{\"active\": false}'), (3, 'not json'), (4, NULL)"
|
|
63
|
+
)
|
|
64
|
+
compiled = Compiler(plugins=[SQLitePlugin()]).compile(Rules, table)
|
|
65
|
+
found = connection.execute(select(table.c.id).where(compiled.predicate)).all()
|
|
66
|
+
assert found == [(1,)]
|
|
67
|
+
engine.dispose()
|
sqlrules_sqlite-1.0.1/PKG-INFO
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: sqlrules-sqlite
|
|
3
|
-
Version: 1.0.1
|
|
4
|
-
Summary: SQLite dialect plugin for SQLRules (REGEXP helpers and JSON).
|
|
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: pydantic,sqlalchemy,sqlite,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-sqlite
|
|
24
|
-
|
|
25
|
-
SQLite dialect plugin for [SQLRules](https://github.com/eddiethedean/sqlrules).
|
|
26
|
-
|
|
27
|
-
## Install
|
|
28
|
-
|
|
29
|
-
```bash
|
|
30
|
-
pip install sqlrules-sqlite
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
## Usage
|
|
34
|
-
|
|
35
|
-
```python
|
|
36
|
-
import sqlite3
|
|
37
|
-
from typing import Annotated, Any
|
|
38
|
-
|
|
39
|
-
from pydantic import BaseModel, Field
|
|
40
|
-
from sqlalchemy import Column, MetaData, String, Table, create_engine, text
|
|
41
|
-
|
|
42
|
-
from sqlrules import Compiler, JsonContains, JsonHasKey
|
|
43
|
-
from sqlrules_sqlite import SQLitePlugin, register_regexp
|
|
44
|
-
|
|
45
|
-
class RowFilter(BaseModel):
|
|
46
|
-
name: Annotated[str, Field(pattern=r"^A")]
|
|
47
|
-
meta: Annotated[dict[str, Any], JsonContains({"active": True}), JsonHasKey("active")]
|
|
48
|
-
|
|
49
|
-
table = Table(
|
|
50
|
-
"rows",
|
|
51
|
-
MetaData(),
|
|
52
|
-
Column("name", String),
|
|
53
|
-
Column("meta", String),
|
|
54
|
-
)
|
|
55
|
-
|
|
56
|
-
compiler = Compiler(plugins=[SQLitePlugin()], dialect="sqlite")
|
|
57
|
-
rules = compiler.compile(RowFilter, table)
|
|
58
|
-
|
|
59
|
-
engine = create_engine("sqlite://")
|
|
60
|
-
with engine.raw_connection() as conn:
|
|
61
|
-
# SQLAlchemy 2 may wrap the DBAPI connection; unwrap if needed.
|
|
62
|
-
dbapi = conn.driver_connection if hasattr(conn, "driver_connection") else conn
|
|
63
|
-
register_regexp(dbapi)
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
## Operators
|
|
67
|
-
|
|
68
|
-
| IR operator | Notes |
|
|
69
|
-
|---|---|
|
|
70
|
-
| `pattern` | `column REGEXP pattern`; call `register_regexp(connection)` |
|
|
71
|
-
| `type_check` | `typeof` / `REGEXP` shape checks; text forms need `register_regexp` |
|
|
72
|
-
| `json_contains` | JSON1 `json_extract` equality for object keys |
|
|
73
|
-
| `json_has_key` | `json_type(column, '$.key') IS NOT NULL` |
|
|
74
|
-
|
|
75
|
-
Case-insensitive patterns (`re.IGNORECASE` / `PatternSpec.ignore_case`) are
|
|
76
|
-
encoded with a `(?i)` prefix understood by `register_regexp`.
|
|
77
|
-
|
|
78
|
-
## Security note
|
|
79
|
-
|
|
80
|
-
`register_regexp` installs a Python `re.search` UDF. Untrusted
|
|
81
|
-
`Field(pattern=...)` values can cause **CPU denial of service** (ReDoS) in
|
|
82
|
-
your process — not SQL injection. Prefer static/allowlisted patterns. See
|
|
83
|
-
[SECURITY](https://sqlrules.readthedocs.io/en/latest/SECURITY.html).
|