Skip to content

Commit

Permalink
Add execute_in_sync_mode functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
tarsil committed Aug 10, 2023
1 parent 30840b9 commit dd1a048
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
7 changes: 2 additions & 5 deletions databasez/testclient.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import asyncio
import os
import typing
from typing import Any

import nest_asyncio
import sqlalchemy as sa
from sqlalchemy.exc import OperationalError, ProgrammingError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy_utils.functions.database import _set_url_database, _sqlite_file_exists, make_url
from sqlalchemy_utils.functions.orm import quote

from databasez import Database, DatabaseURL

nest_asyncio.apply()
from databasez.utils import execute_in_sync_mode


async def _get_scalar_result(engine: typing.Any, sql: typing.Any) -> Any:
Expand Down Expand Up @@ -45,7 +42,7 @@ def __init__(
self.test_db_url = test_database_url._url
self.use_existing = use_existing

asyncio.get_event_loop().run_until_complete(self.setup())
execute_in_sync_mode(self.setup)()

super().__init__(test_database_url, force_rollback=force_rollback, **options)
self.drop = drop_database
Expand Down
21 changes: 21 additions & 0 deletions databasez/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import functools
from typing import Any

import anyio
from anyio._core._eventloop import threadlocals


def execute_in_sync_mode(async_function: Any, raise_error: bool = True) -> Any:
"""
Runs any async function inside a blocking function (sync).
"""

@functools.wraps(async_function)
def wrapper(*args: Any, **kwargs: Any) -> Any:
current_async_module = getattr(threadlocals, "current_async_module", None)
partial_func = functools.partial(async_function, *args, **kwargs)
if current_async_module is not None and raise_error is True:
return anyio.from_thread.run(partial_func)
return anyio.run(partial_func)

return wrapper

0 comments on commit dd1a048

Please sign in to comment.