Database Migrations in Python

end-2-end solution with Alembic

https://medium.com/@johnidouglasmarangon/using-migrations-in-python-sqlalchemy-with-alembic-docker-solution-bd79b219d6a

What is migrations?

In a short answer: change SQL files to source code files

How it works?

Like a version control where we can create a new version, have the head version, and we can go to a  backward and forward version

Setup a Python project

# Start a Postgres database with Docker
docker run --rm -d --name postgres \ 
        -e POSTGRES_USER=myuser -e POSTGRES_PASSWORD=mypassword \
        -p 5432:5432 postgres
  
docker exec -it postgres psql -U myuser -c 'CREATE DATABASE mydb;'


# Install the Alembic
pip install alembic


# Create a main.py
def app():
  print("It is running")


if __name__ == "__main__":
  app()


# Running the project
python main.py

Config the Alembic

Read the DB URI from a envirment variable

Define a name of version table

Define a name of schema

Create a first migration

Migrations in Python (SQLAlchemy + Alembic)

By Johni Douglas Marangon

Migrations in Python (SQLAlchemy + Alembic)

  • 67