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   # pattern → PostgreSQL ~
pip install sqlrules-sqlite       # pattern → SQLite REGEXP
from sqlrules import Compiler
from sqlrules_postgresql import PostgresPlugin

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

Supported constraints (0.3)

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 but has no portable core translator. Use a custom registry translator or a dialect plugin (sqlrules-postgresql, sqlrules-sqlite).

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
pytest tests packages/sqlrules-postgresql/tests packages/sqlrules-sqlite/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.3.0.tar.gz (45.9 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.3.0-py3-none-any.whl (18.0 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for sqlrules-0.3.0.tar.gz
Algorithm Hash digest
SHA256 697b49c04fb69d79df2d42fe002c8c655a8eec2fb97564d8ad5e6ae7e4af26df
MD5 4a9c67f5ec076b19acb6736fd35a86eb
BLAKE2b-256 d5f3368ef99e6248fff787a282362122897be4e98bb198750e987060b4010ffd

See more details on using hashes here.

File details

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

File metadata

  • Download URL: sqlrules-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 18.0 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.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c5567348234103a95ff177486f73ca59baf23b544cb90749d352a7bfc87a9ba9
MD5 fcc0597935397e4bbd1e6a28470091df
BLAKE2b-256 c2e87d1df975122ac605a95da1e569bba51115ab5bfd6fff17f509a50f27265b

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