Skip to main content

Compile constrained Pydantic models into SQLAlchemy WHERE-rule dictionaries.

Project description

SQLRules

Compile constrained Pydantic models into SQLAlchemy WHERE-rule dictionaries.

One package. One job. Deterministic output. Zero database dependency.

from typing import Annotated
from pydantic import BaseModel, Field
from sqlalchemy import Table, Column, Integer, String, MetaData

import sqlrules

metadata = MetaData()

users = Table(
    "users",
    metadata,
    Column("age", Integer),
    Column("name", String),
)

class UserFilter(BaseModel):
    age: Annotated[int, Field(ge=18, le=65)]
    name: Annotated[str, Field(min_length=2)]

rules = sqlrules.compile(UserFilter, users)
# {
#     "age": [users.c.age >= 18, users.c.age <= 65],
#     "name": [func.length(users.c.name) >= 2],
# }

stmt = users.select().where(*sqlrules.where(rules))

Install

pip install sqlrules

Requires Python 3.10+, Pydantic v2, and SQLAlchemy 2.x.

Optional dialect plugins:

pip install sqlrules-postgresql   # ~ / ~*, JSONB, ARRAY, range
pip install sqlrules-sqlite       # REGEXP helper + JSON
pip install sqlrules-mysql        # REGEXP, JSON, full-text
pip install sqlrules-mssql        # JSON + LEN string ops
from typing import Annotated, Any
from pydantic import BaseModel, Field
from sqlrules import Compiler, JsonContains
from sqlrules_postgresql import PostgresPlugin

class RowFilter(BaseModel):
    name: Annotated[str, Field(pattern=r"^A")]
    meta: Annotated[dict[str, Any], JsonContains({"active": True})]

compiler = Compiler(plugins=[PostgresPlugin()], dialect="postgresql")
rules = compiler.compile(RowFilter, table)

Supported constraints (0.4)

Constraint SQLAlchemy expression
gt / ge / lt / le column > / >= / < / <= value
multiple_of column % value == 0
min_length / max_length func.length(column) >= / <= value
Literal[...] column.in_(...)
Enum column.in_(...)

pattern is extracted into IR (PatternSpec) but has no portable core translator. Use a dialect plugin or a custom registry translator.

Dialect markers (JsonContains, ArrayContains, RangeContains, FullTextMatch, …) live in sqlrules.markers and require a dialect plugin.

Unsupported constraints raise UnsupportedConstraintError by default. Use on_unsupported="warn" or "ignore" to change that policy for unknown constraint operators (unsupported types always raise).

Public API

sqlrules.compile(model, table, *, column_map=None, on_unsupported="raise", cache=True)
sqlrules.where(rules)    # flatten all expressions
sqlrules.flatten(rules)  # alias of where()

compiler = sqlrules.Compiler(
    plugins=[...],           # optional SQLRulesPlugin instances
    on_conflict="raise",     # raise | replace | ignore
    dialect=None,            # optional hint for translators
    on_unsupported="raise",
    cache=True,
)

Non-goals

SQLRules is not an ORM, validator, query builder, SQL string generator, migration tool, or database client. It only compiles supported Pydantic constraints into SQLAlchemy expressions.

Documentation

See docs/index.md for the full documentation set, including the spec, API, plugin system, architecture, and roadmap.

Development

pip install -e ".[dev]"
pip install -e packages/sqlrules-postgresql -e packages/sqlrules-sqlite \
  -e packages/sqlrules-mysql -e packages/sqlrules-mssql
pytest tests packages/sqlrules-postgresql/tests packages/sqlrules-sqlite/tests \
  packages/sqlrules-mysql/tests packages/sqlrules-mssql/tests
ruff check .
mypy src/sqlrules
python -m benchmarks.bench_compile

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlrules-0.4.0.tar.gz (53.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlrules-0.4.0-py3-none-any.whl (19.5 kB view details)

Uploaded Python 3

File details

Details for the file sqlrules-0.4.0.tar.gz.

File metadata

  • Download URL: sqlrules-0.4.0.tar.gz
  • Upload date:
  • Size: 53.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for sqlrules-0.4.0.tar.gz
Algorithm Hash digest
SHA256 54e59ab9fe3f64e57c78620ea7e6baf0f33da101810625266e111e3fd83353f1
MD5 91b8b62bf6f638acdd186910616ed99b
BLAKE2b-256 31e3cfc55be3370e112a1bdcc62e2e71fa33943e758e386593d14dc71e1dad9e

See more details on using hashes here.

File details

Details for the file sqlrules-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: sqlrules-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 19.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for sqlrules-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d2608dc2da01455fa43251fd07dcdc28caa43359a41abd94084aaf9a2e18f7b7
MD5 9ce26d5350fa3d0143ced8ec8f5fef42
BLAKE2b-256 22f045471a91e6cd0be16331be466b9d24ccc9468cc65af60677249b80808b0b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page