Skip to main content

offset-free paging for sqlalchemy

Project description

https://travis-ci.org/djrobstep/sqlakeyset.svg?branch=master

This library implements keyset-based paging for SQLAlchemy (both ORM and core).

This library has been tested with PostgreSQL and MariaDB/MySQL. It should work with other SQLAlchemy-supported databases too provided they support row( syntax (see below).

Background

A 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.

sqlakeyset seems to work well so far, but is in its early stages of development, and as such, is alpha software. Treat it accordingly.

Getting Started

Here’s how it works with a typical ORM query:

from sqlakeyset import get_page
from sqlbag import S

from models import Book

with S('postgresql:///books') as s:  # create a session
    q = s.query(Book).order_by(Book.author, Book.title, Book.id)  #

    # gets the first page
    page1 = get_page(q, per_page=20)

    # gets the key for the next page
    next_page = page1.paging.next

    # gets the second page
    page2 = get_page(q, per_page=20, page=next_page)

    # returning to the first page, getting the key
    previous_page = page2.paging.previous

    # the first page again, backwards from the previous page
    page1 = get_page(q, per_page=20, page=previous_page)

    # what if new items were added at the start?
    if page1.paging.has_previous:

        # go back even further
        previous_page = page1.paging.previous
        page1 = get_page(q, per_page=20, page=previous_page)

Under the Hood

sqlakeyset does the following to your query in order to get the paged contents:

  • adds a where clause, to get only rows after the specified row key.

  • if getting the previous page, reverses the order by direction in order the get the rows before the specified bookmark.

  • 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).

  • returns the page contents as an ordinary list that has an attached .paging attribute with the paging information for this and related pages.

Page objects

Paged items/rows are returned in a Page object, which is a vanilla python list, except with an attached Paging object with the paging information.

Properties such as next and previous return a 2-tuple containing the ordering key for the row, and a boolean to specify if the direction is forwards or backwards.

In our above example, the 2-tuple specifying the second page might look like:

('Joseph Heller', 'Catch 22', 123), False

The 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.

The page before this row would be specified as:

('Joseph Heller', 'Catch 22', 123), True

The 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):

None, False

And the last page:

None, True

Keyset Serialization

You will probably want to turn these keysets/bookmarks for passing around. sqlakeyset includes code to do this. To get a serialized bookmark, just add bookmark_ to the name of the property that holds the keyset you want.

Most commonly you’ll want next and previous, so:

>>> page.paging.bookmark_previous
<i:1~i:2015~s:Bad Blood~i:34
>>> page.paging.bookmark_next
>i:1~i:2014~s:Shake It Off~i:31

sqlakeyset uses the python csv row serializer to serialize the bookmark values (using ~ instead of a , as the separator). Direction is indicated by > (forwards/next), or < (backwards/previous) at the start of the string.

Limitations

  • 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.

  • 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).

  • Known MariaDB/MySQL issue: For performing comparisons, sqlakeyset generates row-value syntax similar to the following:

where row('a', 1) > row(name, id)

Indexing support for this syntax in MariaDB/MySQL is apparently faulty. So performance on paging large tables may be poor (Meanwhile, PostgreSQL correctly supports indexing for this syntax).

  • sqlakeyset is alpha software Please be aware that sqlakeyset is in its early stage of development. That said, please use it! Your feedback is most welcome (good or bad).

Documentation

sqlakeyset is in early alpha and documentation other than this README is scarce so far. We are working on remedying this. Watch this space.

Installation

Assuming you have pip installed, all you need to do is install as follows:

$ pip install sqlakeyset

This 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.

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

sqlakeyset-0.1.1559103842.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

sqlakeyset-0.1.1559103842-py2.py3-none-any.whl (11.4 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file sqlakeyset-0.1.1559103842.tar.gz.

File metadata

  • Download URL: sqlakeyset-0.1.1559103842.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.2

File hashes

Hashes for sqlakeyset-0.1.1559103842.tar.gz
Algorithm Hash digest
SHA256 6644d3a6df7fe69d6f3b356befac156c19b1641c5a520cccc82e1d5c9aef0103
MD5 82036822d242e91b6c7bd7f643db1ccd
BLAKE2b-256 68f696568d405dc6eada6cfea8d69d19d9a16b2968555c04e7db73e8b7a86983

See more details on using hashes here.

File details

Details for the file sqlakeyset-0.1.1559103842-py2.py3-none-any.whl.

File metadata

  • Download URL: sqlakeyset-0.1.1559103842-py2.py3-none-any.whl
  • Upload date:
  • Size: 11.4 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.2

File hashes

Hashes for sqlakeyset-0.1.1559103842-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 7f5ec3f66794618d8364743a41a09d75691475a8fcd2b3b0c6d81209d4e12e0a
MD5 8f44d66c9e33caf3131f10e54b3e526f
BLAKE2b-256 305ad997e6cb3b4deee47fc1f14f162f1175b837752cb8c71d1e9b5d28f71e3d

See more details on using hashes here.

Supported by

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