You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
docker exec -it fastapi_expense_backend alembic current
60
60
```
61
+
62
+
### Migrating changes made to the database
63
+
64
+
#### Important notes about containers
65
+
66
+
If your Alembic setup is running inside a container (e.g., a Docker container), you can still check the Alembic state by executing commands inside the container:
67
+
68
+
```shell
69
+
docker exec -it fastapi_expense_backend sh
70
+
```
71
+
72
+
> [!CAUTION]
73
+
> Trying to execute alembic from the host machine instead of inside the container will result in an error:
74
+
> `sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "db" to address: Name or service not known`
75
+
>
76
+
> This error is due to the fact that db is the name of the docker-compose service and also the host name.
77
+
> What would work is: "localhost" instead of "db", however the backend container would not be able to connect to the database url.
78
+
79
+
80
+
#### Generate a migration script
81
+
82
+
After making changes to your database models (schemas), you need to generate a migration script.
83
+
84
+
```shell
85
+
alembic revision --autogenerate -m "Changed expense to transaction table name"
86
+
87
+
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
88
+
INFO [alembic.runtime.migration] Will assume transactional DDL.
89
+
INFO [alembic.autogenerate.compare] Detected removed index 'ix_transactions_id' on 'transactions'
90
+
INFO [alembic.autogenerate.compare] Detected removed table 'transactions'
91
+
INFO [alembic.ddl.postgresql] Detected sequence named 'expenses_id_seq' as owned by integer column 'expenses(id)', assuming SERIAL and omitting
92
+
INFO [alembic.autogenerate.compare] Detected removed index 'ix_expenses_description' on 'expenses'
93
+
INFO [alembic.autogenerate.compare] Detected removed index 'ix_expenses_id' on 'expenses'
94
+
INFO [alembic.autogenerate.compare] Detected removed table 'expenses'
- The --autogenerate flag will automatically compare your models with the current database schema and generate the necessary migration.
99
+
- The `-m` flag allows you to provide a message describing the migration (e.g., "Changed expense to transaction table name").
100
+
101
+
Alembic will generate a migration script in the `alembic/versions/` folder. Review the generated script to ensure it properly represents your intended changes.
102
+
103
+
For example, if you added a new field to your Transaction model, you should see something like this in the migration script:
0 commit comments