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.sqlite import create_engine_sqlite

engine = create_engine_sqlite(
    "file.db",
    journal_mode="WAL",
    timeout=0.5,
    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 = engine.execution_options(
    x_sqlite_begin_mode=None, x_sqlite_foreign_keys="defer"
)

# Make a separate engine for write transactions using "BEGIN IMMEDIATE"
# for eager locking.
engine_w = engine.execution_options(x_sqlite_begin_mode="IMMEDIATE")

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

# read-only transaction
with Session() 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

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-2.3.0.tar.gz (16.0 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-2.3.0-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for sqlalchemy_boltons-2.3.0.tar.gz
Algorithm Hash digest
SHA256 a89ebc01341f0f47f74ddf7f6fa9147ac9ee0d6714d28020720c3912115c889c
MD5 feb783c3d0fa161f0d426a65506f02bf
BLAKE2b-256 c699a718ea364dd5aed7bd291966047c789e028db15a236fc8d1d13df701c9b9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for sqlalchemy_boltons-2.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0ad50ca503772b9d355320ab4daad453bea658f6d52243535935919b573e7154
MD5 07ef74d5e2ad26e1a9800370825023cc
BLAKE2b-256 bcd2b4e6a7e007795b22c96f87a9495a9fa79e6c28de20ae26c41214bdd0de50

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