# PBL2023(後期)最終レポート ## 締め切り - 1/31 23:59 ## 内容 - 作成したアプリの概要 - 開発した機能・API - 工夫した点 - 各種リンク ## 参考 ### マイグレーション #### 例: `User` テーブルに新しいカラム `age` を追加する ##### 0. 変更前の `User` テーブル ``` postgres@localhost:postgres> select * from users; +----+----------+-----------------+ | id | username | hashed_password | |----+----------+-----------------| +----+----------+-----------------+ ``` ##### 1. `models.py` を編集 ```python class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) username = Column(String, unique=True, index=True) hashed_password = Column(String) ``` ↓ ```python class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) username = Column(String, unique=True, index=True) hashed_password = Column(String) age = Column(Integer) ``` ##### 2. マイグレーションファイルを生成 ``` docker-compose run --rm backend alembic revision --autogenerate -m 'Add age column' ``` 出力 ``` INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.ddl.postgresql] Detected sequence named 'users_id_seq' as owned by integer column 'users(id)', assuming SERIAL and omitting INFO [alembic.autogenerate.compare] Detected added column 'users.age' Generating /backend/alembic/versions/7af04073dba9_add_age_column.py ... done ``` `backend/alembic/versions/7af04073dba9_add_age_column.py` というファイルが生成される ##### 3. マイグレーションを実行 ``` docker-compose run --rm backend alembic upgrade head ``` 出力 ``` INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.runtime.migration] Running upgrade 1065ed638c89 -> 7af04073dba9, Add age column ``` ##### 4. 変更後の `User` テーブル ``` postgres@localhost:postgres> select * from users; +----+----------+-----------------+-----+ | id | username | hashed_password | age | |----+----------+-----------------+-----| +----+----------+-----------------+-----+ ```