Skip to content

Commit

Permalink
DB: Add a way to automatically reconnect.
Browse files Browse the repository at this point in the history
Squashed commit of the following:

commit c3d9aa8
Author: funilrys <[email protected]>
Date:   Tue Dec 19 21:49:51 2023 +0100

    Move pooling to engines

commit 17545d5
Author: funilrys <[email protected]>
Date:   Tue Dec 19 19:38:02 2023 +0100

    Add pre_ping.

    Indeed, before this patch, we weren't retrying to reconnect properly.
    This patch fixes the issue by using the pre_ping function of sqlalchemy.

    This patch fixes #346.

    Contributors:
      * @spirillen
  • Loading branch information
funilrys committed Dec 20, 2023
1 parent 912acc7 commit c863378
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions PyFunceble/database/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,9 @@ def init_db_sessions(self) -> "DBSession":

if PyFunceble.sessions.DB_ENGINE is None:
PyFunceble.sessions.DB_ENGINE = sqlalchemy.create_engine(
self.credential.get_uri(), poolclass=sqlalchemy.pool.NullPool
self.credential.get_uri(),
poolclass=sqlalchemy.pool.NullPool,
pool_pre_ping=True,
)

PyFunceble.sessions.DB_FACTORY = sqlalchemy.orm.sessionmaker(
Expand Down Expand Up @@ -176,11 +178,16 @@ def get_new_session(self) -> sqlalchemy.orm.sessionmaker:
"""

engine = sqlalchemy.create_engine(
self.credential.get_uri(), poolclass=sqlalchemy.pool.NullPool
self.credential.get_uri(),
poolclass=sqlalchemy.pool.NullPool,
pool_pre_ping=True,
)

return sqlalchemy.orm.sessionmaker(
bind=engine, autoflush=True, autocommit=False, expire_on_commit=False
bind=engine,
autoflush=True,
autocommit=False,
expire_on_commit=False,
)

@execute_if_authorized(None)
Expand All @@ -190,12 +197,13 @@ def get_new_pool_session(self) -> sqlalchemy.orm.sessionmaker:
Create and return a new session.
"""

engine = sqlalchemy.create_engine(
self.credential.get_uri(),
)
engine = sqlalchemy.create_engine(self.credential.get_uri(), pool_pre_ping=True)

return sqlalchemy.orm.sessionmaker(
bind=engine, autoflush=True, autocommit=False, expire_on_commit=False
bind=engine,
autoflush=True,
autocommit=False,
expire_on_commit=False,
)

def close(self) -> "DBSession":
Expand Down

0 comments on commit c863378

Please sign in to comment.