Skip to main content

Utilities that should've been inside SQLAlchemy but aren't

Project description

sqlalchemy_boltons

SQLAlchemy is great. However, it doesn't have everything built-in. Some important things are missing, and need to be "bolted on".

(Name inspired from boltons. Not affiliated.)

sqlite

SQLAlchemy doesn't automatically fix pysqlite's broken transaction handling. This module implements the usual fix for that well-known broken behaviour, and also adds extra features on top of that.

You can customize, on a per-engine or per-connection basis:

Here's a minimal example:

from sqlalchemy.orm import sessionmaker
from sqlalchemy_boltons import sqlite as sq

engine = sq.create_engine_sqlite("file.db", create_engine_args={"echo": True})

# Configure the engine to use a plain "BEGIN" to start transactions and
# and to use deferred enforcement of foreign keys (recommended!)
engine = sq.Options.new(
    timeout=0.5,
    begin="DEFERRED",
    foreign_keys="DEFERRED",
    recursive_triggers=True,
    trusted_schema=False,  # set to True if the db file is from a trusted source
    schemas={"main": sq.SchemaOptions.new(journal="WAL", synchronous="NORMAL")},
).apply(engine)

# Make a separate engine for write transactions using "BEGIN IMMEDIATE"
# for eager locking.
engine_w = sq.Options.apply_lambda(
    engine, lambda options: options.evolve(begin="IMMEDIATE")
)

# Construct a sessionmaker for each engine.
SessionR = sessionmaker(engine)
SessionW = sessionmaker(engine_w)

# read-only transaction
with SessionR() as session:
    session.execute(select(...))

# lock the database eagerly for writing
with SessionW() as session:
    session.execute(update(...))

orm

orm.RelationshipComparator

Somedays you really wish you could write something like:

# Find every parent that has at least one child.
Parent1 = aliased(Parent)
select(Parent1).where(
    exists().select_from(Child).where(Child.parent == Parent1)  # this doesn't work
)

But it doesn't work. You get an exception. You try various other things but it just won't produce the right subquery. You find tons of people online saying you must resign yourself to writing the explicit filtering condition, writing out .where(Child.parent_id == Parent1.id). Like a caveman. Why even bother using an ORM at this point? If you're lucky, you find yourself reading mail archives from a decade ago with somewhat of a solution, but it's not obvious how to make it work with table aliases. Despair is setting in.

But lucky you, you can now use this library:

from sqlalchemy_boltons.orm import RelationshipComparator as Rel

# Find every parent that has at least one child.
Parent1 = aliased(Parent)
select(Parent1).where(
    exists().select_from(Child).where(Rel(Child.parent) == Parent1)
)  #                                  ^^^^            ^

Hope is restored. This even works on self-referential tables!

orm.IdKey

IdKey holds the primary key information for an ORM instance. This is useful for passing a reference to an ORM object across different sessions and/or threads. This is implemented in terms of Session.identity_key and Session.get, so you don't have to mess around with Session.merge.

with Session() as s1:
    instance = s1.execute(sa.select(MyClass).where(...)).one()
    key = IdKey.from_instance(instance)

# ...later, maybe in a different thread:
with Session() as s2:
    instance = key.get_one(s2)  # raises sqlalchemy.exc.NoResultFound if object doesn't exist anymore

core

core.bytes_startswith(sql_expr, prefix: bytes)

This function constructs a SQL expression equivalent to sql_expr.startswith(prefix) but using comparison operators instead. The intended use case is efficiently searching a BLOB-like column that has an index on it.

temporary_table

Create a temporary table so you can write things like:

from sqlalchemy import sa
from sqlalchemy_boltons.temporary import temporary_table

tmp_table_def = Table("ids", sa.MetaData(), sa.Column("id", Integer, primary_key=True))

...

my_ids = [1, 23, 4, 5, 67, 89]

with Session() as s:
    with temporary_table(s, tmp_table_def) as tmp:
        s.execute(sa.insert(tmp), [{"id": x} for x in my_ids])
        results = s.execute(sa.select(SomeTable).join(tmp, tmp.c.id == SomeTable.id)).all()

reset

PostgreSQL and MS SQL both require additional things to be done to fully clean up before reusing a connection. A mere "ROLLBACK" is insufficient. By default, SQLAlchemy doesn't do those things.

from sqlalchemy_boltons.reset import install_reset_auto

engine = create_engine(..., pool_reset_on_return=False)
install_reset_auto(engine)

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

sqlalchemy_boltons-4.0.1.tar.gz (25.6 kB view details)

Uploaded Source

Built Distribution

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

sqlalchemy_boltons-4.0.1-py3-none-any.whl (17.3 kB view details)

Uploaded Python 3

File details

Details for the file sqlalchemy_boltons-4.0.1.tar.gz.

File metadata

  • Download URL: sqlalchemy_boltons-4.0.1.tar.gz
  • Upload date:
  • Size: 25.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.2

File hashes

Hashes for sqlalchemy_boltons-4.0.1.tar.gz
Algorithm Hash digest
SHA256 62f999e4f5b06182f61d705b207a6cf0afffa95563d332c9dfc985e5d4744a45
MD5 fcf9d57d31b46b555045769bde1ffd47
BLAKE2b-256 6574a8e41576d473afb76a3d4948479778a201eab6d623d58b362e37a7d1c65c

See more details on using hashes here.

File details

Details for the file sqlalchemy_boltons-4.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for sqlalchemy_boltons-4.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 45213a7cdd5b9699ff8f7e77ffd14600c702d909192ee3ef8ead042c33b87f67
MD5 d2806c259296f2f0aa10cc4ad4d3337a
BLAKE2b-256 950a1f3b5ce22f36df660d98ddd5c510d8e3c818fc4250d5d53b176bc0011bf5

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