1010
1111{% - if cookiecutter .orm == "ormar" % }
1212from {{cookiecutter .project_name }}.db .config import database
13+ {% - if cookiecutter .db_info .name != "none" and cookiecutter .enable_migrations == "False" % }
14+ from sqlalchemy .engine import create_engine
15+ from {{cookiecutter .project_name }}.db .meta import meta
16+ from {{cookiecutter .project_name }}.db .models import load_all_models
17+ {% - endif % }
1318{% - endif % }
1419
1520{% - if cookiecutter .orm == "sqlalchemy" % }
2126)
2227from sqlalchemy .orm import sessionmaker
2328
29+ {% - if cookiecutter .db_info .name != "none" and cookiecutter .enable_migrations == "False" % }
30+ from {{cookiecutter .project_name }}.db .meta import meta
31+ from {{cookiecutter .project_name }}.db .models import load_all_models
32+ {% - endif % }
33+
2434
2535def _setup_db (app : FastAPI ) -> None :
2636 """
@@ -47,11 +57,34 @@ def _setup_db(app: FastAPI) -> None:
4757
4858{% if cookiecutter .enable_redis == "True" % }
4959def _setup_redis (app : FastAPI ) -> None :
60+ """
61+ Initialize redis connection.
62+
63+ :param app: current FastAPI app.
64+ """
5065 app .state .redis_pool = aioredis .ConnectionPool .from_url (
5166 str (settings .redis_url ),
5267 )
5368{% - endif % }
5469
70+ {% - if cookiecutter .db_info .name != "none" and cookiecutter .enable_migrations == "False" % }
71+ {% - if cookiecutter .orm in ["ormar" , "sqlalchemy" ] % }
72+ async def _create_tables () -> None :
73+ """Populates tables in the database."""
74+ load_all_models ()
75+ {% - if cookiecutter .orm == "ormar" % }
76+ engine = create_engine (str (settings .db_url ))
77+ with engine .connect () as connection :
78+ meta .create_all (connection )
79+ engine .dispose ()
80+ {% - elif cookiecutter .orm == "sqlalchemy" % }
81+ engine = create_async_engine (str (settings .db_url ))
82+ async with engine .begin () as connection :
83+ await connection .run_sync (meta .create_all )
84+ await engine .dispose ()
85+ {% - endif % }
86+ {% - endif % }
87+ {% - endif % }
5588
5689def startup (app : FastAPI ) -> Callable [[], Awaitable [None ]]:
5790 """
@@ -67,9 +100,14 @@ def startup(app: FastAPI) -> Callable[[], Awaitable[None]]:
67100 async def _startup () -> None : # noqa: WPS430
68101 {% - if cookiecutter .orm == "sqlalchemy" % }
69102 _setup_db (app )
70- {% elif cookiecutter .orm == "ormar" % }
103+ {% - elif cookiecutter .orm == "ormar" % }
71104 await database .connect ()
72105 {% - endif % }
106+ {% - if cookiecutter .db_info .name != "none" and cookiecutter .enable_migrations == "False" % }
107+ {% - if cookiecutter .orm in ["ormar" , "sqlalchemy" ] % }
108+ await _create_tables ()
109+ {% - endif % }
110+ {% - endif % }
73111 {% - if cookiecutter .enable_redis == "True" % }
74112 _setup_redis (app )
75113 {% - endif % }
0 commit comments