- Add table definition to the
db/tablesdirectory. - Import the table class in the
db/tables/__init__.pyfile. - Create a database migration.
- Run database migration.
Table Definition
Let’s create aUsersTable, copy the following code to db/tables/user.py
db/tables/user.py
db/tables/__init__.py file:
db/tables/__init__.py
Create a database revision
Run the alembic command to create a database migration in the dev container:Migrate dev database
Run the alembic command to migrate the dev database:Optional: Add test user
Now lets’s add a test user. Copy the following code todb/tables/test_add_user.py
db/tables/test_add_user.py
Migrate production database
We recommended migrating the production database by setting the environment variableMIGRATE_DB = True and restarting the production service. This runs alembic -c db/alembic.ini upgrade head from the entrypoint script at container startup.
Update infra/prd_resources.py
infra/prd_resources.py
Update the ECS Task Definition
Because we updated the Environment Variables, we need to update the Task Definition:Update the ECS Service
After updating the task definition, redeploy the production application:Manually migrate prodution database
Another approach is to SSH into the production container to run the migration manually. Your ECS tasks are already enabled with SSH access. Run the alembic command to migrate the production database:How the migrations directory was created
These commands have been run and are described for completeness
- After running the above command, the
db/migrationsdirectory should be created. - Update
alembic.ini- set
script_location = db/migrations - uncomment
blackhook in[post_write_hooks]
- set
- Update
db/migrations/env.pyfile following this link - Add the following function to
configureto only include tables in the target_metadata
db/migrations/env.py