Skip to content
This repository was archived by the owner on Mar 31, 2026. It is now read-only.

Repository files navigation

Database Setup Tools for SQLModel / SQLAlchemy

CodeQLTest

Simplified database lifecycle and session management based on SQLModel / SQLAlchemy.

Any contributions are welcome! But we only accept pull requests that come with tests.

Installation

pip install database-setup-tools

Features

  • Database creation on app startup
  • Thread-safe database session manager
  • Opinionated towards SQLModel but feasible with any other framework or pure sqlalchemy
  • Easily use a local database in your tests

Usage

In order to use this library, you need some SQLModel or SQLAlchemy tables and a URI to connect to your database. With this in place, the DatabaseSetup instance can be created - which contains all provided tools and also automatically creates the database including all tables.

fromsqlmodelimportField, SQLModelfromdatabase_setup_toolsimportDatabaseSetupclassUser(SQLModel, table=True):
""" User database entity / table """id: int=Field(index=True, primary_key=True)
name: str# create database & tables, establish connection with session pooldatabase_setup=DatabaseSetup(
model_metadata=SQLModel.metadata,
database_uri="postgresql+psycopg2://postgres:postgres@localhost:5432/database",
)

Note: The DatabaseSetup class acts as singleton, so if you create multiple instances with the same set of parameters, you will always get the same instance back instead of creating a new one.

After the setup is created, you can get a scoped session via the provided session manager and use it for database transactions.

# get scoped sessionsession=next(database_setup.session_manager.get_session())
# do stuff in sessionuser=User(name="Alice")
session.add(user)
session.commit()

The DatabaseSetup instance also provides lifecycle methods allowing to manually control the database:

database_setup.create_database()
database_setup.drop_database()

Development

Testing

  1. Spin up databases for local integration tests: docker-compose -f tests/docker-compose.yaml up -d
  2. Create virtual environment & install dependencies: poetry install
  3. Run tests: poetry run pytest

About

Easy to understand and use python tools that help you to create databases and interact with them

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages