Database Tables
Phidata templates come pre-configured with SqlAlchemy and alembic to manage databases. The general workflow to add a table is:
- Add table definition to the
db/tables
directory. - Import the table class in the
db/tables/__init__.py
file. - Create a database migration.
- Run database migration.
Table Definition
Let’s create a UsersTable
, copy the following code to db/tables/user.py
Update the db/tables/__init__.py
file:
Creat 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 to db/tables/test_add_user.py
Run the script to add a test adding a user:
Migrate production database
We recommended migrating the production database by setting the environment variable MIGRATE_DB = True
and restarting the production service. This runs alembic -c db/alembic.ini upgrade head
from the entrypoint script at container startup.
Update the workspace/prd_resources.py
file
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
The migrations directory was created using:
- After running the above command, the
db/migrations
directory should be created. - Update
alembic.ini
- set
script_location = db/migrations
- uncomment
black
hook in[post_write_hooks]
- set
- Update
db/migrations/env.py
file following this link - Add the following function to
configure
to only include tables in the target_metadata
Was this page helpful?