Skip to content

Conversation

@GitMarco27
Copy link
Contributor

Add support for reusing an existing SQLAlchemy AsyncEngine + type hinting in DatabaseSessionService

Link to Issue or Description of Change

2. Or, if no issue exists, describe the change:

Problem:

In real-world applications, ADK is often used alongside existing ORMs or database operations. We typically:

  • Already have a configured database engine with specific settings
  • Want to reuse existing connection pools to avoid resource exhaustion
  • Need consistent database configuration across their entire application
  • Prefer to manage database lifecycle (connection pooling, timeouts, etc.) in a centralized way (e.g., in the lifespan of a FastAPI application).

Previously, DatabaseSessionService forced users to create a new engine by passing a connection string, which resulted in:

  • Duplicate engine instances for the same database
  • Multiple connection pools competing for resources
  • Potentially inconsistent configuration between ADK and the rest of the application
  • No control over engine lifecycle and settings from the application side

Solution:

This PR adds the ability to pass an existing SQLAlchemy AsyncEngine to DatabaseSessionService.

Core Changes:

  • Added db_engine parameter to DatabaseSessionService.__init__() to accept a pre-configured AsyncEngine
  • Implemented @overload decorators for type hints and IDE support
  • Updated constructor to accept either db_url or db_engine (mutually exclusive)
  • Added validation to ensure exactly one of the two parameters is provided

More infos:

  • Maintains backward compatibility (no breaking changes)
  • Python's @overload for compile-time type checking

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.
  • All unit tests pass locally.

New tests added:

  • test_database_session_service_with_db_url() - Tests both positional and keyword argument patterns (backward compatibility)
  • test_database_session_service_with_db_engine() - Tests new engine parameter functionality
  • test_database_session_service_requires_one_argument() - Tests validation logic (ensures exactly one parameter provided)

New Feature - Reusing existing engine

from sqlalchemy.ext.asyncio import create_async_engine
from google.adk.sessions.database_session_service import DatabaseSessionService

# Create engine with custom configuration (application-level)
engine = create_async_engine(
    "postgresql+asyncpg://user:pass@localhost:5432/mydb",
    echo=True,
    pool_size=20,
    max_overflow=10,
    pool_pre_ping=True,
    pool_recycle=3600,
)

# Reuse the engine in ADK
session_service = DatabaseSessionService(db_engine=engine)

# Check that CRUD operations work with reused engine
session = await session_service.create_session(
    app_name="my_app",
    user_id="user_123",
    state={"key": "value"}
)
assert session is not None

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

…g an existing SQAlchemy AsyncEngine + type hinting
@gemini-code-assist
Copy link

Summary of Changes

Hello @GitMarco27, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the DatabaseSessionService by allowing it to reuse an already configured SQLAlchemy AsyncEngine. This addresses common challenges in real-world applications where ADK needs to integrate with existing ORMs, ensuring consistent database configurations, preventing resource exhaustion from duplicate connection pools, and offering centralized control over the database lifecycle. The update maintains backward compatibility and includes enhanced type hinting and validation for a more robust and developer-friendly experience.

Highlights

  • Flexible Database Engine Initialization: The DatabaseSessionService now supports initialization using either a database URL string (db_url) or an existing SQLAlchemy AsyncEngine instance (db_engine), providing greater flexibility for integrating with existing application database setups.
  • Type Hinting with Overloads: Python's @overload decorators have been implemented for the __init__ method of DatabaseSessionService, enhancing type checking and IDE support for the two distinct initialization patterns (with db_url or db_engine).
  • Mutual Exclusivity Validation: Robust validation has been added to ensure that exactly one of db_url or db_engine is provided during DatabaseSessionService initialization, preventing ambiguous or incorrect configurations.
  • Backward Compatibility Maintained: The changes are fully backward compatible, meaning existing code that initializes DatabaseSessionService with a db_url will continue to function without modification.
  • Comprehensive Unit Tests: New unit tests have been added to cover the new initialization logic, including tests for db_url (positional and keyword arguments), db_engine, and the mutual exclusivity validation.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@adk-bot adk-bot added the services [Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc label Nov 15, 2025
Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a valuable enhancement to DatabaseSessionService by allowing the reuse of an existing SQLAlchemy AsyncEngine. This change improves resource management and configuration consistency when integrating with larger applications. The implementation is well-executed, using @overload for clear type hinting and maintaining backward compatibility. The validation logic for the new parameters is robust, and the accompanying unit tests are thorough. I have one minor suggestion to improve type hint consistency in the __init__ method.

…mplementation (no overload)

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

services [Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants