-
-
Notifications
You must be signed in to change notification settings - Fork 130
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix (#1): Use NullPool with SQLAlchemy in Celery tasks
Need to improve this for the future, but at least we don't run into asyncio issues due to shared connections improperly closed and handled across celery tasks.
- Loading branch information
1 parent
e2da37c
commit fae98a8
Showing
3 changed files
with
31 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,29 @@ | ||
from polar.config import settings | ||
from polar.ext.sqlalchemy import sql | ||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine | ||
from sqlalchemy.orm import sessionmaker | ||
from sqlalchemy.pool import NullPool | ||
|
||
from polar.config import settings | ||
from polar.ext.sqlalchemy import sql | ||
|
||
engine = create_async_engine(settings.postgres_dsn, echo=True) | ||
AsyncSessionLocal = sessionmaker( | ||
engine, | ||
autocommit=False, | ||
autoflush=False, | ||
expire_on_commit=False, | ||
class_=AsyncSession, | ||
) | ||
def create_sessionmaker(is_celery: bool = False) -> sessionmaker: | ||
engine_options = dict(echo=settings.DEBUG) | ||
if is_celery: | ||
# TODO: Change pooling strategy for celery workers. | ||
# In the meantime, we're using NullPool to avoid | ||
# issues with asyncio in Celery. | ||
engine_options.update(dict(poolclass=NullPool)) | ||
|
||
engine = create_async_engine(settings.postgres_dsn, **engine_options) | ||
return sessionmaker( | ||
engine, | ||
autocommit=False, | ||
autoflush=False, | ||
expire_on_commit=False, | ||
class_=AsyncSession, | ||
) | ||
|
||
|
||
AsyncSessionLocal = create_sessionmaker() | ||
|
||
|
||
__all__ = ["sql", "engine", "AsyncSessionLocal", "AsyncSession"] | ||
__all__ = ["sql", "AsyncSessionLocal", "AsyncSession"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters