Alembic is a powerful tool to manage database generating migrations and versions of tables, views and etc enabling a easy management of your database.
#Installing the alembic
pip install alembic
#starting the alembic
alembic init alembic
Now you have to edit the alembic.ini and put your connectionstring using the field sqlalchemy.url
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
# (new in 1.5.5)
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to ${script_location}/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:${script_location}/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = driver://user:pass@localhost/dbname
# [post_write_hooks]
# This section defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner,
# against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Now let’s create the first table definition
alembic revision -m "create account table"
He gonna create a migration file and you can edit it and put your table definition
"""create user table
Revision ID:
Revises:
Create Date: 2022-04-25 21:41:11.988502
"""
from alembic import op
import datetime
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'xxxxxx'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'account',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.String(128), nullable=False),
sa.Column('description', sa.Unicode(200)),
sa.Column('created', sa.DateTime, default=sa.func.now()),
sa.Column('updated', sa.DateTime, onupdate=sa.func.now()),
)
def downgrade():
op.drop_table('account')
Now let’s run it to create the table
alembic upgrade head
Voila, your table is created! Now lets edit this table adding a column
alembic revision -m "Add a column"
Now he created another migration file to edit and put your changes
"""Add a column
Revision ID:
Revises:
Create Date: 2022-04-26 23:16:56.501818
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'xxxx'
down_revision = 'yyy'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('account', sa.Column('birthdate', sa.DateTime))
op.add_column('account', sa.Column('email', sa.String(128)))
op.add_column('account', sa.Column('ip_source', sa.String(16)))
op.add_column('account', sa.Column('location', sa.String(128)))
def downgrade():
op.drop_column('account', 'birthdate')
op.drop_column('account', 'email')
op.drop_column('account', 'ip_source')
op.drop_column('account', 'location')
Now let’s just run again and everything is voila!
alembic revision -m "Add a column"
Ref: Welcome to Alembic’s documentation! — Alembic 1.7.7 documentation (sqlalchemy.org)