From 4156b2287cc029788abbe0899a2f121ae875b3fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mois=C3=A9s?= <7888669+moisses89@users.noreply.github.com> Date: Mon, 13 Jan 2025 13:59:30 +0100 Subject: [PATCH] Add ipython profile to query the database (#60) --- README.md | 14 ++++++++++++++ docker/web/Dockerfile | 1 + scripts/db_profile.py | 28 ++++++++++++++++++++++++++++ scripts/fill_db.py | 0 4 files changed, 43 insertions(+) create mode 100644 scripts/db_profile.py delete mode 100644 scripts/fill_db.py diff --git a/README.md b/README.md index c9d6129..724ef81 100644 --- a/README.md +++ b/README.md @@ -46,5 +46,19 @@ To create a new migration based on changes made to the model code, run the follo alembic revision --autogenerate -m "MIGRATION TITLE" ``` +### Querying the database via Python Shell in Docker +To open an interactive Python shell within a Docker container and query the database, use the following command: +``` + docker exec -it safe-decoder-service-web-1 python -m IPython -i ./scripts/db_profile.py +``` +Example usage: +``` +In [11]: contracts = await Contract.get_all(session) + +In [12]: contracts[0].address +Out[12]: b'J\xdb\xaa\xc7\xbc#\x9e%\x19\xcb\xfd#\x97\xe0\xf7Z\x1d\xe3U\xc8' + +``` + ## Contributors [See contributors](https://github.com/safe-global/safe-decoder-service/graphs/contributors) diff --git a/docker/web/Dockerfile b/docker/web/Dockerfile index 06ab332..5f8f6d0 100644 --- a/docker/web/Dockerfile +++ b/docker/web/Dockerfile @@ -17,6 +17,7 @@ RUN set -ex \ && apt-get install -y --no-install-recommends $buildDeps \ && pip install -U --no-cache-dir wheel setuptools pip \ && pip install --no-cache-dir -r requirements.txt \ + && pip install --no-cache-dir ipython \ && apt-get purge -y --auto-remove $buildDeps \ && rm -rf /var/lib/apt/lists/* \ && find /usr/local \ diff --git a/scripts/db_profile.py b/scripts/db_profile.py new file mode 100644 index 0000000..d3ac378 --- /dev/null +++ b/scripts/db_profile.py @@ -0,0 +1,28 @@ +""" +Ipython profile to enable on startup database interactions +""" + +import asyncio + +from sqlmodel.ext.asyncio.session import AsyncSession + +from app.datasources.db.database import get_engine +from app.datasources.db.models import * # noqa: F401, F403 + +session: AsyncSession | None = None + + +async def restore_session(): + """ + Close default session an open a new one. + + :return: + """ + global session + if session: + await session.close() + + session = AsyncSession(get_engine(), expire_on_commit=False) + + +asyncio.run(restore_session()) diff --git a/scripts/fill_db.py b/scripts/fill_db.py deleted file mode 100644 index e69de29..0000000