Database Creation and Deletion with SQLAlchemy-Utils

  • Share this:

Code introduction


This function uses the database_exists, create_database, and drop_database functions from SQLAlchemy-Utils to check, create, or delete a database.


Technology Stack : SQLAlchemy, SQLAlchemy-Utils

Code Type : Function

Code Difficulty : Intermediate


                
                    
from sqlalchemy_utils import database_exists, create_database, drop_database
from sqlalchemy import create_engine

def create_drop_database(engine, db_name, drop_if_exists=False):
    """
    Create a new database and optionally drop it if it already exists.
    
    :param engine: SQLAlchemy engine to use
    :param db_name: Name of the database to create or drop
    :param drop_if_exists: If True, drop the database if it already exists before creating a new one
    """
    if drop_if_exists and database_exists(engine, db_name):
        drop_database(engine, db_name)
    create_database(engine, db_name)