{"id":31534504,"url":"https://github.com/ronik-v/sqlalchemy-querytools","last_synced_at":"2025-10-04T05:40:52.555Z","repository":{"id":315750454,"uuid":"1060684806","full_name":"ronik-v/sqlalchemy-querytools","owner":"ronik-v","description":"lib for select queries (search, sort)","archived":false,"fork":false,"pushed_at":"2025-09-27T15:24:30.000Z","size":37,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-27T16:18:06.712Z","etag":null,"topics":["orm-library","search","select","sorting","sqlalchemy"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/sqlalchemy-querytools/0.1.0/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ronik-v.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-09-20T11:36:27.000Z","updated_at":"2025-09-27T15:24:00.000Z","dependencies_parsed_at":"2025-09-20T14:50:44.943Z","dependency_job_id":null,"html_url":"https://github.com/ronik-v/sqlalchemy-querytools","commit_stats":null,"previous_names":["ronik-v/sqlalchemy-querytools"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ronik-v/sqlalchemy-querytools","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronik-v%2Fsqlalchemy-querytools","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronik-v%2Fsqlalchemy-querytools/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronik-v%2Fsqlalchemy-querytools/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronik-v%2Fsqlalchemy-querytools/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ronik-v","download_url":"https://codeload.github.com/ronik-v/sqlalchemy-querytools/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronik-v%2Fsqlalchemy-querytools/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":277859158,"owners_count":25889887,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-01T02:00:09.286Z","response_time":88,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["orm-library","search","select","sorting","sqlalchemy"],"created_at":"2025-10-04T05:40:48.885Z","updated_at":"2025-10-04T05:40:52.548Z","avatar_url":"https://github.com/ronik-v.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# sqlalchemy-querytools\n\nLightweight helpers to build SQLAlchemy `SELECT` queries with common list-table features: **search**, **sort**, and *\n*pagination**.  \nEach tool accepts a `sqlalchemy.Select` and returns a modified `Select`. Designed to be composed — ideal for APIs, CRUD\nendpoints and list pages.\n\n**Version:** `0.1.0`  \n**License:** MIT\n\n---\n\n## Table of contents\n\n- [Purpose](#purpose)\n- [Install](#install)\n- [Quick example](#quick-example)\n- [Public API](#public-api)\n- [Behavior details](#behavior-details)\n- [Examples](#examples)\n    - [Search (ALL_FIELDS)](#search-all_fields)\n    - [Search (DATE_FIELDS)](#search-date_fields)\n    - [Sort (ASC / DESC) and null placement](#sort-asc--desc-and-null-placement)\n    - [Pagination (limit / offset)](#pagination-limit--offset)\n    - [Compose: search + sort + paginate](#compose-search--sort--paginate)\n- [Tests](#tests)\n- [Notes / gotchas](#notes--gotchas)\n- [Contributing](#contributing)\n- [License](#license)\n\n---\n\n## Purpose\n\n`sqlalchemy-querytools` provides three small, composable builders that make it easy to add common list-table features to\nSQLAlchemy queries:\n\n- `SearchQuery` — builds `WHERE` clauses for text/date searching across model fields.\n- `SortQuery` — builds `ORDER BY` with ASC/DESC and controls null placement.\n- `PaginationQuery` — applies `LIMIT` and `OFFSET`.\n\nEach builder returns a `sqlalchemy.Select` that you then execute with your session.\n\n---\n\n## Install\n\nIf published to PyPI:\n\n```bash\npip install sqlalchemy-querytools\n```\n\nOr install locally:\n\n```bash\npip install -e .\n```\n\nRequirements: SQLAlchemy (version compatible with your project). For running tests: `pytest`.\n\n---\n\n## Quick example\n\n```python\nfrom sqlalchemy import select\nfrom sqlalchemy.orm import sessionmaker\n\nfrom sqlalchemy_querytools import SearchQuery, SortQuery, PaginationQuery\nfrom sqlalchemy_querytools.types import SearchType, SortType\n\n# assume engine, Session, and User model are already defined\nsession = Session()\n\ntable_fields = {\n    \"name\": User.name,\n    \"email\": User.email,\n    \"created_at\": User.created_at,\n}\n\nstmt = select(User)\n\n# search -\u003e sort -\u003e paginate\nstmt = SearchQuery(stmt, SearchType.ALL_FIELDS, table_fields, \"alice\").build()\nstmt = SortQuery(stmt, SortType.ASC, table_fields, \"name\", null_last=False).build()\nstmt = PaginationQuery(stmt, offset=0, limit=20).build()\n\nusers = session.execute(stmt).scalars().all()\n```\n\n---\n\n## Public API\n\nExports (from `__all__`):\n\n- `SearchQuery(stmt: Select, query_tool_type: SearchType, table_fields_relation: TableFields, search_value: str)`\n    - `.build() -\u003e Select`\n- `SortQuery(stmt: Select, query_tool_type: SortType, table_fields_relation: TableFields, sort_field: str, null_last: bool = False)`\n    - `.build() -\u003e Select`\n- `PaginationQuery(stmt: Select, offset: int, limit: int)`\n    - `.build() -\u003e Select`\n- `SearchType` — enum values: `ALL_FIELDS`, `DATE_FIELDS`\n- `SortType` — enum values: `ASC`, `DESC`\n- `TableFields` — `dict[str, InstrumentedAttribute]` (mapping names → SQLAlchemy attributes)\n\n---\n\n## Behavior details\n\n**SearchQuery**\n\n- `SearchType.ALL_FIELDS`\n    - Builds `ilike('%value%')` for each mapped field.\n    - If a mapped field is non-text, the implementation casts to `String` before applying `ilike`.\n    - If `search_value` is empty or whitespace, no filters are added and the original `Select` is returned.\n- `SearchType.DATE_FIELDS`\n    - Expects `search_value` parseable via `datetime.fromisoformat` (e.g. `\"2020-01-01\"`), converts to `date` and\n      compares equality against `Date`/`DateTime` fields.\n    - Invalid date string → `ValueError` from `datetime.fromisoformat`.\n- Unknown `SearchType` → `TypeError(\"Uncorrected search type\")`.\n\n**SortQuery**\n\n- Looks up `sort_field` in `table_fields_relation`. Missing key → `KeyError`.\n- `SortType.ASC` → `asc(field)`; `SortType.DESC` → `desc(field)`.\n- `null_last=True` uses `.nullslast()`, otherwise `.nullsfirst()`.\n- Unknown `SortType` → `TypeError(\"Uncorrected sort type\")`.\n\n**PaginationQuery**\n\n- Applies `.limit(limit).offset(offset)` on the `Select`.\n\n---\n\n## Examples\n\n### Search (ALL_FIELDS)\n\n```python\nfrom sqlalchemy_querytools import SearchQuery\nfrom sqlalchemy_querytools.types import SearchType\n\nstmt = select(User)\nsearch = SearchQuery(stmt, SearchType.ALL_FIELDS, {\"name\": User.name, \"email\": User.email}, \"ann\")\nresult = session.execute(search.build()).scalars().all()\n```\n\n### Search (DATE_FIELDS)\n\n```python\nsearch = SearchQuery(select(User), SearchType.DATE_FIELDS, {\"created_at\": User.created_at}, \"2020-01-01\")\nrows = session.execute(search.build()).scalars().all()\n# Note: the date string must be ISO-like and parseable by datetime.fromisoformat\n```\n\n### Sort (ASC / DESC) and null placement\n\n```python\nfrom sqlalchemy_querytools import SortQuery\nfrom sqlalchemy_querytools.types import SortType\n\n# ascending, NULLs first (default)\nq = SortQuery(select(User), SortType.ASC, {\"name\": User.name}, \"name\", null_last=False)\n\n# descending, NULLs last\nq2 = SortQuery(select(User), SortType.DESC, {\"name\": User.name}, \"name\", null_last=True)\n```\n\nIf `sort_field` is not in `table_fields_relation`, `_use_extension()` will raise `KeyError` — this makes invalid input\nexplicit.\n\n### Pagination\n\n```python\nfrom sqlalchemy_querytools import PaginationQuery\n\npage = PaginationQuery(select(User), offset=20, limit=10)\nstmt = page.build()\nrows = session.execute(stmt).scalars().all()\n```\n\n### Compose: search + sort + paginate\n\n```python\nstmt = select(User)\nstmt = SearchQuery(stmt, SearchType.ALL_FIELDS, table_fields, \"alice\").build()\nstmt = SortQuery(stmt, SortType.ASC, table_fields, \"name\", null_last=True).build()\nstmt = PaginationQuery(stmt, offset=0, limit=25).build()\nrows = session.execute(stmt).scalars().all()\n```\n\n---\n\n## Tests\n\nProject includes `pytest` tests which demonstrate expected behaviors:\n\n- Case-insensitive partial search\n- Unicode / Cyrillic handling\n- Special characters and emoji support\n- Date searching behavior (including tests that skip if implementation raises `ValueError`)\n- Sorting behavior with `NULL` values\n\nRun tests:\n\n```bash\npip install -r requirements_dev.txt  # sqlalchemy, pytest, etc.\npytest -q\n```\n\n---\n\n## Notes / gotchas\n\n- `ilike` and case-insensitivity depend on your DB backend and column collations.\n- `SearchQuery` casts non-text fields to `String` for `ALL_FIELDS` search; ensure `table_fields_relation` lists only\n  intended columns to search.\n- Date searching uses `datetime.fromisoformat`; invalid input raises `ValueError`. Tests are aware of this behavior.\n- Tools return `Select` objects; you must execute them with your session (e.g. `session.execute(stmt).scalars().all()`).\n- `SortQuery` intentionally raises `KeyError` for missing fields to fail fast with user-provided sort parameters.\n\n---\n\n## Contributing\n\n1. Fork the repo.\n2. Create a branch for your change.\n3. Add tests for new behaviors or fixes.\n4. Open a pull request.\n\nPlease include tests for DB-sensitive behavior (e.g. collation, null ordering) where applicable.\n\n---\n\n## License\n\nThis project is licensed under the MIT License — see `LICENSE` in the repository for the full text.\n\n```\nMIT License\n\nCopyright (c) 2025\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction...\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fronik-v%2Fsqlalchemy-querytools","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fronik-v%2Fsqlalchemy-querytools","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fronik-v%2Fsqlalchemy-querytools/lists"}