-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Add asyncpg SQLAlchemy engine factory for Entra authentication #48368
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Matthew Boentoro (mattboentoro)
merged 7 commits into
Azure:main
from
pabloacan:feature/GH-48365-asyncpg-sqlalchemy-entra-authentication
Aug 17, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7245686
feat(azure-postgresql-auth): add asyncpg SQLAlchemy engine factory
pabloacan 9ebd34d
Merge branch 'main' into feature/GH-48365-asyncpg-sqlalchemy-entra-au…
pabloacan 0289fa9
Fix asyncpg factory pylint documentation
pabloacan 43f8a88
Merge branch 'main' into feature/GH-48365-asyncpg-sqlalchemy-entra-au…
pabloacan 3b71c1b
Merge branch 'main' into feature/GH-48365-asyncpg-sqlalchemy-entra-au…
pabloacan b57f2e6
Merge branch 'main' into feature/GH-48365-asyncpg-sqlalchemy-entra-au…
pabloacan 410e9ae
Merge branch 'main' into feature/GH-48365-asyncpg-sqlalchemy-entra-au…
mattboentoro File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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
82 changes: 82 additions & 0 deletions
82
sdk/postgresql/azure-postgresql-auth/azure_postgresql_auth/sqlalchemy/asyncpg.py
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| # ------------------------------------------------------------------------- | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. See License.txt in the project root for | ||
| # license information. | ||
| # ------------------------------------------------------------------------- | ||
|
|
||
| """asyncpg integration for SQLAlchemy asynchronous engines.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from azure.core.credentials_async import AsyncTokenCredential | ||
|
|
||
| try: | ||
| from sqlalchemy.engine import URL, make_url | ||
| from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine | ||
| except ImportError as e: | ||
| raise ImportError( | ||
| "SQLAlchemy dependencies are not installed. Install them with: pip install azure-postgresql-auth[sqlalchemy]" | ||
| ) from e | ||
|
|
||
| from azure_postgresql_auth.core import get_entra_conninfo_async | ||
| from azure_postgresql_auth.errors import CredentialValueError, EntraConnectionValueError | ||
|
|
||
|
|
||
| def create_asyncpg_engine( | ||
| url: str | URL, | ||
| credential: AsyncTokenCredential, | ||
| **kwargs: Any, | ||
| ) -> AsyncEngine: | ||
| """Create an asyncpg SQLAlchemy engine authenticated with Microsoft Entra ID. | ||
|
|
||
| The returned engine obtains Entra connection information asynchronously whenever | ||
| SQLAlchemy creates a physical connection for its pool. | ||
|
|
||
| :param url: SQLAlchemy URL using the ``postgresql+asyncpg`` dialect. | ||
| :type url: str or ~sqlalchemy.engine.URL | ||
| :param credential: Credential used to acquire Microsoft Entra access tokens. | ||
| :type credential: ~azure.core.credentials_async.AsyncTokenCredential | ||
| :return: An asynchronous SQLAlchemy engine. | ||
| :rtype: ~sqlalchemy.ext.asyncio.AsyncEngine | ||
| :raises ~azure_postgresql_auth.CredentialValueError: If ``credential`` is not an | ||
| ``AsyncTokenCredential``. | ||
| :raises ImportError: If ``asyncpg`` is not installed. | ||
|
|
||
| Additional keyword arguments are forwarded to ``create_async_engine``. Values | ||
| supplied through ``connect_args`` are forwarded to ``asyncpg.connect``. | ||
| """ | ||
| if not isinstance(credential, AsyncTokenCredential): | ||
| raise CredentialValueError("credential is required and must be an AsyncTokenCredential for asyncpg") | ||
|
|
||
| try: | ||
| import asyncpg | ||
| except ImportError as e: | ||
| raise ImportError( | ||
| "asyncpg dependencies are not installed. Install them with: pip install azure-postgresql-auth[asyncpg]" | ||
| ) from e | ||
|
|
||
| parsed_url = make_url(url) | ||
| connect_args = parsed_url.translate_connect_args(username="user", database="database") | ||
| connect_args.update(dict(parsed_url.query)) | ||
| connect_args.update(kwargs.pop("connect_args", {})) | ||
|
|
||
| if "sslmode" in connect_args and "ssl" not in connect_args: | ||
| connect_args["ssl"] = connect_args["sslmode"] | ||
| connect_args.pop("sslmode", None) | ||
|
|
||
| async def async_creator() -> Any: | ||
| try: | ||
| entra_conninfo = await get_entra_conninfo_async(credential) | ||
| except Exception as e: | ||
| raise EntraConnectionValueError("Could not retrieve Entra credentials") from e | ||
|
|
||
| connection_kwargs = { | ||
| **connect_args, | ||
| "user": connect_args.get("user", entra_conninfo["user"]), | ||
| "password": connect_args.get("password", entra_conninfo["password"]), | ||
| } | ||
| return await asyncpg.connect(**connection_kwargs) | ||
|
|
||
| return create_async_engine(parsed_url, async_creator=async_creator, **kwargs) |
This file contains hidden or 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 hidden or 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 hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.