Registry / database / sqlalchemy-utils

sqlalchemy-utils

JSON →
library0.42.1pypypi✓ verified 25d ago

SQLAlchemy-Utils is a library that provides various utility functions, new data types, and helpers for SQLAlchemy. It extends SQLAlchemy's functionality by offering additional features to simplify common database tasks like managing database existence, custom column types (e.g., ChoiceType, UUIDType, EmailType), and ORM helpers. The library is actively maintained with frequent updates, typically a few minor releases per year, and is currently at version 0.42.1.

pip install sqlalchemy-utils
INSTALL
IMPORT
SIG · SQLALCHEMY-UTILS
S
sqlalchemy-utils
databasepythonv0.42.1
Install
3.3s avg
Import
1110ms
Disk
42MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.42.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.160s · 43.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.3s · import 1.060s · 42MB
42MB installed
● package 42MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

database_exists
from sqlalchemy_utils import database_exists
create_database
from sqlalchemy_utils import create_database
drop_database
from sqlalchemy_utils import drop_database
ChoiceType
from sqlalchemy_utils import ChoiceType
Timestamp
from sqlalchemy_utils import Timestamp
generic_repr
from sqlalchemy_utils import generic_repr

This quickstart demonstrates how to use `sqlalchemy-utils` to create and manage a PostgreSQL database programmatically, define a model with a custom `ChoiceType`, and perform basic ORM operations. It utilizes `database_exists`, `create_database`, and `ChoiceType` from the utility library. Environment variables are used for database credentials for security and flexibility. To run this, ensure a PostgreSQL server is accessible and you have `psycopg2-binary` or `psycopg` installed.

import os from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy_utils import database_exists, create_database, drop_database, ChoiceType # --- Database Setup --- DB_USER = os.environ.get('DB_USER', 'testuser') DB_PASS = os.environ.get('DB_PASS', 'testpass') DB_HOST = os.environ.get('DB_HOST', 'localhost') DB_NAME = os.environ.get('DB_NAME', 'test_db') DATABASE_URL = f"postgresql://{DB_USER}:{DB_PASS}@{DB_HOST}/{DB_NAME}" engine = create_engine(DATABASE_URL) # Create database if it doesn't exist if not database_exists(engine.url): create_database(engine.url) print(f"Database '{DB_NAME}' created.") else: print(f"Database '{DB_NAME}' already exists.") Session = sessionmaker(bind=engine) Base = declarative_base() # --- Define a Model with ChoiceType --- class TaskPriority: LOW = 'low' MEDIUM = 'medium' HIGH = 'high' class Task(Base): __tablename__ = 'tasks' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) priority = Column(ChoiceType(TaskPriority, impl=String(10))) def __repr__(self): return f"<Task(id={self.id}, name='{self.name}', priority='{self.priority}')>" # --- ORM Operations --- Base.metadata.create_all(engine) # Create tables session = Session() # Add tasks task1 = Task(name="Write documentation", priority=TaskPriority.HIGH) task2 = Task(name="Review code", priority=TaskPriority.MEDIUM) task3 = Task(name="Deploy update", priority=TaskPriority.LOW) session.add_all([task1, task2, task3]) session.commit() # Query tasks print("\nAll tasks:") for task in session.query(Task).all(): print(task) # Clean up (optional: uncomment to drop the database) # session.close() # drop_database(engine.url) # print(f"Database '{DB_NAME}' dropped.")
Debug
Known issues
breakingVersion 0.42.0 dropped support for Python 3.7 and 3.8. Users on these Python versions must either upgrade their Python environment or pin `sqlalchemy-utils<0.42.0` to avoid compatibility issues.
fix
Upgrade Python to 3.9+ or pin `sqlalchemy-utils` version: `pip install 'sqlalchemy-utils<0.42.0'`.
affects: >=0.42.0
breakingVersion 0.42.0 dropped support for SQLAlchemy 1.3. SQLAlchemy 2.0 support was added in 0.40.0 and subsequent versions include fixes for SQLAlchemy 2.0.x compatibility. Ensure your SQLAlchemy version is 1.4 or 2.x.
fix
Upgrade SQLAlchemy to 1.4.x or 2.x: `pip install 'sqlalchemy>=1.4,<3.0'`.
affects: >=0.42.0
gotchaWhen using `ColorType`, be aware of a potential import name conflict if the `colour-science` package is also installed, as it shares the same import name (`colour`) as the package `sqlalchemy-utils` expects. This was fixed in 0.39.0 to avoid crashes.
fix
Upgrade to `sqlalchemy-utils>=0.39.0` or avoid installing `colour-science` alongside older versions.
affects: <0.39.0
gotcha`create_database` and `database_exists` functions handle different database dialects (e.g., PostgreSQL, MySQL, SQLite) differently. For PostgreSQL and MySQL, they connect to a default/master database to check/create the target database, requiring appropriate credentials and server access, not just database-specific access.
fix
Ensure the provided URL has credentials for a database with sufficient privileges to create new databases (e.g., `postgres` user for PostgreSQL) and that the database server is running.
affects: all
gotchaA specific `AttributeError` could occur with `Sequence` defaults in `instant_defaults_listener`. This issue was resolved in version 0.42.1.
fix
Upgrade to `sqlalchemy-utils>=0.42.1`.
affects: 0.42.0
gotchaWhen using SQLAlchemy with specific database backends (e.g., PostgreSQL, MySQL), the corresponding database driver (e.g., `psycopg2` for PostgreSQL, `mysqlclient` for MySQL) must be installed separately. A `ModuleNotFoundError` will occur if the required driver is missing during engine creation.
fix
Install the appropriate database driver for your chosen backend, e.g., `pip install psycopg2-binary` for PostgreSQL or `pip install mysqlclient` for MySQL.
affects: all
gotcha`sqlalchemy-utils` relies on SQLAlchemy for database connectivity. When connecting to a specific database (e.g., PostgreSQL, MySQL), the corresponding SQLAlchemy database driver (e.g., `psycopg2` for PostgreSQL, `pymysql` for MySQL) must be installed separately. This error indicates the required driver is missing.
fix
Install the appropriate database driver for your chosen SQLAlchemy dialect. For PostgreSQL, run: `pip install psycopg2-binary`. For MySQL, run: `pip install pymysql`.
affects: all
Upgrade
Version history
0.42.1latest on PyPI · released Dec 13, 2025
Audit
Dependencies
SQLAlchemyrequiredCore dependency for all functionality.
psycopg2-binaryoptionalRequired for PostgreSQL database operations (e.g., create_database, delete_database) if psycopg3 is not used.
psycopgoptionalRequired for PostgreSQL database operations with psycopg3 (supported from 0.41.0).
colouroptionalFor the ColorType functionality.
Agent activity
20 hits · last 30 days
node
16
Meta
1
OpenAI (training)
1
Resources
sqlalchemy-utils — pip install sqlalchemy-utils · libregistry