Skip to content

feat: add async engine support for storage_engine#35

Merged
doganarif merged 6 commits into
mainfrom
support-async-storage-engine
Nov 11, 2025
Merged

feat: add async engine support for storage_engine#35
doganarif merged 6 commits into
mainfrom
support-async-storage-engine

Conversation

@doganarif
Copy link
Copy Markdown
Owner

@doganarif doganarif commented Nov 9, 2025

Summary by Sourcery

Add support for AsyncEngine in storage backend by adapting session creation and DDL operations for both synchronous and asynchronous SQLAlchemy engines

New Features:

  • Allow storage_engine parameter to accept both sync and async SQLAlchemy engines

Enhancements:

  • Automatically choose between sessionmaker and async_sessionmaker based on engine type with an _is_async_storage flag
  • Wrap create_tables and drop_tables in asyncio.run to support async engines

Summary by cubic

Add support for SQLAlchemy AsyncEngine in storage_engine to enable async databases while keeping existing sync setups working.

  • New Features

    • storage_engine now accepts Engine or AsyncEngine.
    • Sessions remain sync by binding sessionmaker to AsyncEngine.sync_engine when async is used.
    • create_tables and drop_tables run DDL via conn.run_sync for async engines, with asyncio.run or a thread-pool fallback when an event loop is active; sync behavior unchanged.
  • Bug Fixes

    • Prevent RuntimeError by detecting active event loops and running async DDL in a thread pool when needed.

Written for commit 911dfb0. Summary will update automatically on new commits.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Nov 9, 2025

Reviewer's Guide

Adds support for both sync and async storage_engine by updating session creation and table management methods to detect AsyncEngine and run DDL operations in an async context via asyncio.run.

Class diagram for updated Radar initialization and table management

classDiagram
    class Radar {
        - storage_engine: Engine | AsyncEngine
        - SessionLocal
        - _is_async_storage: bool
        + create_tables()
        + drop_tables()
    }
    class Engine
    class AsyncEngine
    Radar --> Engine : uses as storage_engine
    Radar --> AsyncEngine : uses as storage_engine
    Radar --> SessionLocal : creates
    class sessionmaker
    class async_sessionmaker
    Radar --> sessionmaker : uses for sync engine
    Radar --> async_sessionmaker : uses for async engine
Loading

Flow diagram for session creation based on storage_engine type

flowchart TD
    A["Radar.__init__"] --> B{Is storage_engine AsyncEngine?}
    B -- Yes --> C["SessionLocal = async_sessionmaker(...)"]
    B -- No --> D["SessionLocal = sessionmaker(...)"]
    C --> E["_is_async_storage = True"]
    D --> F["_is_async_storage = False"]
Loading

Flow diagram for create_tables and drop_tables supporting async engines

flowchart TD
    A["create_tables() or drop_tables() called"] --> B{Is storage_engine AsyncEngine?}
    B -- Yes --> C["Run DDL in async context using asyncio.run"]
    B -- No --> D["Run DDL synchronously"]
Loading

File-Level Changes

Change Details Files
Support async or sync storage_engine in initializer
  • Expanded storage_engine type to Union[Engine, AsyncEngine]
  • Selected async_sessionmaker for AsyncEngine or sessionmaker otherwise
  • Introduced _is_async_storage flag
fastapi_radar/radar.py
Enable create_tables to handle async engines
  • Branch on AsyncEngine to run DDL via asyncio.run
  • Use async with engine.begin() and conn.run_sync for metadata.create_all
  • Fallback to sync create_all for Engine
fastapi_radar/radar.py
Enable drop_tables to handle async engines
  • Wrap metadata.drop_all in asyncio.run when AsyncEngine
  • Use async with engine.begin() and conn.run_sync for drop_all
  • Keep sync drop_all path for Engine
fastapi_radar/radar.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Avoid using asyncio.run inside FastAPI context since it will fail if there’s already a running loop; consider using the existing event loop or an async startup event to run DDL commands.
  • The _is_async_storage attribute is set but not used anywhere else—either leverage it in your logic or remove it to keep the code clean.
  • There’s duplicated async create/drop table logic; consider extracting a helper method to reduce redundancy and improve maintainability.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Avoid using asyncio.run inside FastAPI context since it will fail if there’s already a running loop; consider using the existing event loop or an async startup event to run DDL commands.
- The `_is_async_storage` attribute is set but not used anywhere else—either leverage it in your logic or remove it to keep the code clean.
- There’s duplicated async create/drop table logic; consider extracting a helper method to reduce redundancy and improve maintainability.

## Individual Comments

### Comment 1
<location> `fastapi_radar/radar.py:395` </location>
<code_context>
+                    async with self.storage_engine.begin() as conn:
+                        await conn.run_sync(Base.metadata.create_all)
+
+                asyncio.run(_create_tables())
+            else:
+                Base.metadata.create_all(bind=self.storage_engine)
</code_context>

<issue_to_address>
**issue (bug_risk):** Using asyncio.run may cause issues if already inside an event loop.

If called from an async context, asyncio.run will raise RuntimeError. Consider checking for an active event loop or providing an async alternative.
</issue_to_address>

### Comment 2
<location> `fastapi_radar/radar.py:414` </location>
<code_context>
+                async with self.storage_engine.begin() as conn:
+                    await conn.run_sync(Base.metadata.drop_all)
+
+            asyncio.run(_drop_tables())
+        else:
+            Base.metadata.drop_all(bind=self.storage_engine)
</code_context>

<issue_to_address>
**issue (bug_risk):** Potential event loop conflict with asyncio.run in drop_tables.

Refactor to allow async usage or clearly document that this function cannot be called from within an active event loop.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread fastapi_radar/radar.py Outdated
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 1 file

Prompt for AI agents (all 2 issues)

Understand the root cause of the following 2 issues and fix them.


<file name="fastapi_radar/radar.py">

<violation number="1" location="fastapi_radar/radar.py:400">
Calling `asyncio.run(_create_tables())` will crash when `create_tables()` is triggered from within an active event loop (e.g., a FastAPI startup hook). This regresses legitimate usage because `asyncio.run` raises `RuntimeError` if the loop is already running.</violation>

<violation number="2" location="fastapi_radar/radar.py:419">
The new `asyncio.run(_drop_tables())` call will raise `RuntimeError` if `drop_tables()` is executed while an event loop is active (typical in async FastAPI lifecycle code), causing the operation to fail.</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

Comment thread fastapi_radar/radar.py Outdated
Comment thread fastapi_radar/radar.py Outdated
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

Add support for SQLAlchemy AsyncEngine in storage_engine parameter.
Update create_tables() and drop_tables() to handle both sync and async engines.
Use async_sessionmaker for async engines, sessionmaker for sync engines.
Maintain backward compatibility with existing sync engine usage.

Fixes #32
Use sync_engine from AsyncEngine for session operations to keep
the existing synchronous session usage pattern throughout the
codebase (middleware, capture, api, etc.)

This approach:
- Uses AsyncEngine for DDL operations (create_tables, drop_tables)
- Uses sync_engine for session operations (middleware, capture, etc.)
- Maintains type safety and passes mypy checks
Detect if an event loop is already running (e.g., FastAPI startup hooks)
and run async DDL operations in a thread pool to avoid RuntimeError.

This ensures create_tables() and drop_tables() work correctly:
- When called directly (no event loop)
- When called from async context (active event loop)
- When called from FastAPI startup hooks

Fixes the RuntimeError regression for legitimate async usage patterns.
@doganarif doganarif force-pushed the support-async-storage-engine branch from 45f4ba7 to 604601e Compare November 11, 2025 01:27
@doganarif doganarif merged commit 386e945 into main Nov 11, 2025
5 checks passed
@doganarif doganarif deleted the support-async-storage-engine branch November 11, 2025 01:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant