{"id":13908273,"url":"https://github.com/djrobstep/sqlakeyset","last_synced_at":"2025-05-14T12:08:04.811Z","repository":{"id":37546232,"uuid":"66554135","full_name":"djrobstep/sqlakeyset","owner":"djrobstep","description":"offset-free paging for sqlalchemy","archived":false,"fork":false,"pushed_at":"2025-02-09T01:58:10.000Z","size":439,"stargazers_count":371,"open_issues_count":3,"forks_count":52,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-04-04T14:27:32.876Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"unlicense","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/djrobstep.png","metadata":{"files":{"readme":"README.rst","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}},"created_at":"2016-08-25T12:00:44.000Z","updated_at":"2025-03-25T18:08:40.000Z","dependencies_parsed_at":"2024-06-18T15:36:15.651Z","dependency_job_id":"a103ede7-c5e6-4f85-8a98-7411c91e188c","html_url":"https://github.com/djrobstep/sqlakeyset","commit_stats":{"total_commits":198,"total_committers":28,"mean_commits":7.071428571428571,"dds":0.3939393939393939,"last_synced_commit":"499a1f8c0686b74ed586d8b4c6ead31511f924f9"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/djrobstep%2Fsqlakeyset","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/djrobstep%2Fsqlakeyset/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/djrobstep%2Fsqlakeyset/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/djrobstep%2Fsqlakeyset/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/djrobstep","download_url":"https://codeload.github.com/djrobstep/sqlakeyset/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248469136,"owners_count":21108963,"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","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":[],"created_at":"2024-08-06T23:02:36.006Z","updated_at":"2025-04-11T19:45:50.835Z","avatar_url":"https://github.com/djrobstep.png","language":"Python","funding_links":[],"categories":["HarmonyOS","Python"],"sub_categories":["Windows Manager"],"readme":"sqlakeyset: offset-free paging for sqlalchemy\n=============================================\n\n.. image:: https://img.shields.io/circleci/build/gh/djrobstep/sqlakeyset?label=tests\n    :alt: Tests\n    :target: https://circleci.com/gh/djrobstep/sqlakeyset\n    \n.. image:: https://img.shields.io/pypi/v/sqlakeyset\n    :alt: PyPI\n    :target: https://pypi.org/project/sqlakeyset/\n    \n.. image:: https://img.shields.io/conda/vn/conda-forge/sqlakeyset.svg\n    :alt: conda-forge\n    :target: https://anaconda.org/conda-forge/sqlakeyset\n\n.. image:: https://readthedocs.org/projects/sqlakeyset/badge/\n   :alt: Documentation @ readthedocs\n   :target: https://sqlakeyset.readthedocs.io/\n\nsqlakeyset implements keyset-based paging for SQLAlchemy (both ORM and core). **Now with full SQLAlchemy 2 support and type hints!**\n\nThis library is tested with PostgreSQL, MariaDB/MySQL and SQLite. It should work with many other SQLAlchemy-supported databases, too; but caveat emptor - you should verify the results are correct.\n\nPython version compatibility\n----------------------------\n\n**Notice:** In accordance with Python end-of-life dates, we've stopped supporting Python versions earlier than 3.8.\n\nIf you really need it, the latest version to support Python 2 is 0.1.1559103842, Python 3.4 is 1.0.1679209451, and Python 3.7 is 2.0.1733532871; but you'll miss out on all the latest features and bugfixes from newer versions. You should be upgrading anyway!\n\nBackground\n----------\n\nA lot of people use SQL's ``OFFSET`` syntax to implement paging of query results. The trouble with that is, the more pages you get through, the slower your query gets. Also, if the results you're paging through change frequently, it's possible to skip over or repeat results between pages. Keyset paging avoids these problems: Selecting even the millionth page is as fast as selecting the first.\n\n\nGetting Started\n---------------\n\nHere's how it works with a typical SQLAlchemy 2.0-style query (or SQLAlchemy 1.3 Core):\n\n.. code-block:: python\n\n    from sqlalchemy import create_engine, select\n    from sqlalchemy.orm import Session\n    from sqlakeyset import select_page\n\n    from models import Book\n\n    engine = create_engine('postgresql:///books')\n    with Session(engine) as s:\n        q = select(Book).order_by(Book.author, Book.title, Book.id)\n\n        # gets the first page\n        page1 = select_page(s, q, per_page=20)\n\n        # gets the key for the next page\n        next_page = page1.paging.next\n\n        # gets the second page\n        page2 = select_page(s, q, per_page=20, page=next_page)\n\n        # returning to the first page, getting the key\n        previous_page = page2.paging.previous\n\n        # the first page again, backwards from the previous page\n        page1 = select_page(s, q, per_page=20, page=previous_page)\n\n        # what if new items were added at the start?\n        if page1.paging.has_previous:\n\n            # go back even further\n            previous_page = page1.paging.previous\n            page1 = select_page(s, q, per_page=20, page=previous_page)\n\n\nIf you're still using legacy (i.e. SQLAlchemy 1.3-style) ORM queries, you can\nuse ``get_page`` instead, which has an identical API other than the omission of\nthe session/connection argument:\n\n.. code-block:: python\n\n    from sqlakeyset import get_page\n    with Session(engine) as s:\n        q = s.query(Book).order_by(Book.author, Book.title, Book.id)\n        page1 = get_page(q, per_page=20)\n        # ...\n\nWe also support asyncio, and the API is near-identical - just import from\n``sqlakeyset.asyncio`` and pass an ``AsyncSession``:\n\n.. code-block:: python\n\n    from sqlalchemy import select\n    from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\n    from sqlakeyset.asyncio import select_page\n    engine = create_async_engine('postgresql:///books')\n    async with AsyncSession(engine) as s:\n        q = select(Book).order_by(Book.author, Book.title, Book.id)\n        page1 = await select_page(s, q, per_page=20)\n        # ...\n\n\nUnder the Hood\n--------------\n\nsqlakeyset does the following to your query in order to get the paged contents:\n\n- adds a where clause, to get only rows after the specified row key.\n- if getting the previous page, reverses the ``order by`` direction in order the get the rows *before* the specified bookmark.\n- adds a limit clause, to fetch only enough items to fill the page, plus one additional (this additional row is used only to test for the existence of further pages after the current one, and is discarded from the results).\n- returns the page contents as an ordinary list that has an attached ``.paging`` attribute with the paging information for this and related pages.\n\n\nPage objects\n------------\n\nPaged items/rows are returned in a ``Page`` object, which is a vanilla python list extended by an attached ``Paging`` object containing paging information.\n\nProperties such as `next` and `previous` return a pair containing the ordering key for the row, and a boolean to specify if the direction is forwards or backwards. We refer to such a pair ``(keyset, backwards)`` as a *marker*.\n\nIn our above example, the marker specifying the second page might look like:\n\n.. code-block:: python\n\n    ('Joseph Heller', 'Catch 22', 123), False\n\nThe `False` means the query will fetch the page *after* the row containing Catch 22. This tuple contains two elements, title and id, to match the order by clause of the query.\n\nThe page before this row would be specified as:\n\n.. code-block:: python\n\n    ('Joseph Heller', 'Catch 22', 123), True\n\nThe first and last pages are fetched with `None` instead of a tuple, so for the first page (this is also the default if the page parameter is not specified):\n\n.. code-block:: python\n\n    None, False\n\nAnd the last page:\n\n.. code-block:: python\n\n    None, True\n\nKeyset Serialization\n--------------------\n\nYou will probably want to turn these markers into strings for passing around. ``sqlakeyset`` includes code to do this, and calls the resulting strings *bookmarks*. To get a serialized bookmark, just add ``bookmark_`` to the name of the property that holds the keyset you want.\n\nMost commonly you'll want ``next`` and ``previous``, so:\n\n.. code-block:: python\n\n    \u003e\u003e\u003e page.paging.bookmark_previous\n    \u003ci:1~i:2015~s:Bad Blood~i:34\n    \u003e\u003e\u003e page.paging.bookmark_next\n    \u003ei:1~i:2014~s:Shake It Off~i:31\n\n``sqlakeyset`` uses the python csv row serializer to serialize the bookmark values (using ``~`` instead of a ``,`` as the separator). Direction is indicated by ``\u003e`` (forwards/next), or ``\u003c`` (backwards/previous) at the start of the string.\n\nLimitations\n-----------\n\n- **Golden Rule:** Always ensure your keysets are unique per row. If you violate this condition you risk skipped rows and other nasty problems. The simplest way to do this is to always include your primary key column(s) at the end of your ordering columns.\n\n- Any rows containing null values in their keysets **will be omitted from the results**, so your ordering columns should be ``NOT NULL``. (This is a consequence of the fact that comparisons against ``NULL`` are always false in SQL.) This may change in the future if we work out an alternative implementation; but for now we recommend using ``coalesce`` as a workaround if you need to sort by nullable columns:\n\n.. code-block:: python\n\n    from sqlalchemy import func\n    with Session(engine) as s:\n        # If Book.cost can be NULL:\n        q = select(Book).order_by(func.coalesce(Book.cost, 0), Book.id)\n        # Assuming cost is non-negative, page1 will start with books where cost is null:\n        page1 = select_page(s, q, per_page=20)\n\n- If you're using the in-built keyset serialization, this only handles basic data/column types so far (strings, ints, floats, datetimes, dates, booleans, and a few others). The serialization can be extended to serialize more advanced types as necessary (documentation on this is forthcoming).\n\n\nDocumentation\n-------------\n\nOther than this README, there is some more detailed API documentation autogenerated from docstrings, which you can `read online at readthedocs.io \u003chttps://sqlakeyset.readthedocs.io/\u003e`_ or build yourself with e.g. ``make -C doc html``.\n\n\nInstallation\n------------\n\nAssuming you have `pip \u003chttps://pip.pypa.io\u003e`_ installed, all you need to do is install as follows:\n\n.. code-block:: shell\n\n    $ pip install sqlakeyset\n\nThis will install sqlakeyset and also sqlalchemy if not already installed. Obviously you'll need the necessary database driver for your chosen database to be installed also.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdjrobstep%2Fsqlakeyset","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdjrobstep%2Fsqlakeyset","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdjrobstep%2Fsqlakeyset/lists"}