Skip to main content

Build SQLAlchemy 2 WHERE clauses from nested JSON-friendly filter rules validated with Pydantic.

Project description

approck-sqlalchemy-query-builder

Take a filter tree as JSON (from a REST body, WebSocket message, or stored config), validate it with Pydantic, and turn it into a SQLAlchemy 2 WHERE fragment you can attach to your own select(). You keep full control over columns, joins, and ordering; the library only maps allowed fields to real Column objects so arbitrary JSON never touches the database layer directly.

Requirements

  • Python 3.10+
  • SQLAlchemy 2.0+
  • Pydantic 2.x

Install

pip install approck-sqlalchemy-query-builder

Or with uv:

uv add approck-sqlalchemy-query-builder

Usage

1. Define the filter in JSON — nested groups use condition ("AND" / "OR") and rules; each leaf is id (logical name), operator, and value:

{
  "condition": "AND",
  "rules": [
    { "id": "status", "operator": "=", "value": "active" },
    {
      "condition": "OR",
      "rules": [
        { "id": "role", "operator": "=", "value": "admin" },
        { "id": "role", "operator": "=", "value": "moderator" }
      ]
    }
  ]
}

2. Parse and bind to real columnsQuery.model_validate_json / Query.model_validate accept the same shape as json.loads. You pass a whitelist map_columns from logical id to SQLAlchemy columns (only those keys can appear in SQL):

import sqlalchemy as sa
from approck_sqlalchemy_query_builder import Query, query_filter

# Dict from your stack: JSON.parse, await request.json(), Pydantic/FastAPI body, etc.
filter_payload = {
    "condition": "AND",
    "rules": [
        {"id": "status", "operator": "=", "value": "active"},
        {
            "condition": "OR",
            "rules": [
                {"id": "role", "operator": "=", "value": "admin"},
                {"id": "role", "operator": "=", "value": "moderator"},
            ],
        },
    ],
}
query = Query.model_validate(filter_payload)

statement = sa.select(MyModel)
statement = query_filter(
    statement,
    map_columns={
        "status": MyModel.status,
        "role": MyModel.role,
    },
    query=query,
)

For a raw JSON string (e.g. straight from the wire), use Query.model_validate_json(body).

Supported operators

=, >, <, >=, <=, !=, in, not in.

Datetime columns

If the column type name contains DATETIME, integer values are treated as Unix timestamps (milliseconds if the value is larger than “now” in seconds). Strings are parsed with python-dateutil and normalized to UTC.

Unknown columns

With skip_unknown_column=True, rules whose id is missing from map_columns are skipped instead of raising ValueError.

Development

Clone the repository and install dependencies with uv:

uv sync --group dev
uv run pytest
uv run ruff check .
uv run ruff format --check .
uv run mypy approck_sqlalchemy_query_builder

See CONTRIBUTING.md for pull request guidelines.

License

MIT — see LICENSE.

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

approck_sqlalchemy_query_builder-1.0.4.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

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

File details

Details for the file approck_sqlalchemy_query_builder-1.0.4.tar.gz.

File metadata

  • Download URL: approck_sqlalchemy_query_builder-1.0.4.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for approck_sqlalchemy_query_builder-1.0.4.tar.gz
Algorithm Hash digest
SHA256 28c7fb9d39471166b9eddb0770e3d782bc4745402747aa2cb553ef0089e53392
MD5 3f27345e3db615ab61052d016c9b7439
BLAKE2b-256 5d1481706f553f2485f9f7b2dfa120346249864782aaf25192807b365a321041

See more details on using hashes here.

File details

Details for the file approck_sqlalchemy_query_builder-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: approck_sqlalchemy_query_builder-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 6.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for approck_sqlalchemy_query_builder-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 974ddd9d829d61d0e116f51d22b7e294331f3306f5efdc1cbe4b1681f0db86f4
MD5 f1cd5394ae9c8627dce154cfd9897295
BLAKE2b-256 84fd4aa8340bcc1b47dc15b38ac8f45e2ad2886507fbedd915202ed6b549fb20

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