Skip to content

Commit

Permalink
fix: updated sqlalchemy samples & unpin advanced-alchemy (#3693)
Browse files Browse the repository at this point in the history
* fix: updated sqlalchemy samples

* docs: updated file locations
  • Loading branch information
cofin authored Aug 24, 2024
1 parent d1ef753 commit b3cf2fd
Show file tree
Hide file tree
Showing 19 changed files with 479 additions and 409 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ repos:
- id: trailing-whitespace
exclude: "tests/unit/test_openapi/test_typescript_converter/test_converter.py"
- repo: https://github.com/provinzkraut/unasyncd
rev: "v0.7.3"
rev: "v0.8.1"
hooks:
- id: unasyncd
additional_dependencies: ["ruff"]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.6.1"
rev: "v0.6.2"
hooks:
- id: ruff
args: ["--fix"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from __future__ import annotations

from litestar import Litestar
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
from litestar.contrib.sqlalchemy.plugins.init.config.asyncio import autocommit_before_send_handler
from litestar.plugins.sqlalchemy import (
SQLAlchemyAsyncConfig,
SQLAlchemyInitPlugin,
async_autocommit_before_send_handler,
)

config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///:memory:",
before_send_handler=autocommit_before_send_handler,
connection_string="sqlite+aiosqlite:///:memory:", before_send_handler=async_autocommit_before_send_handler
)
plugin = SQLAlchemyInitPlugin(config=config)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from sqlalchemy import select

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin

if TYPE_CHECKING:
from typing import Tuple
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin

if TYPE_CHECKING:
from typing import Any, Dict, List
Expand Down Expand Up @@ -38,11 +38,10 @@ async def add_item(data: Dict[str, Any], db_session: AsyncSession) -> List[Dict[


async def init_db(app: Litestar) -> None:
async with app.state.db_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
async with config.get_engine().begin() as conn:
await conn.run_sync(Base.metadata.create_all)


config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///todo_async.sqlite")
plugin = SQLAlchemyInitPlugin(config=config)
app = Litestar(route_handlers=[add_item], plugins=[plugin], on_startup=[init_db])
app = Litestar(route_handlers=[add_item], plugins=[plugin], on_startup=[init_db], debug=True)
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Sequence

from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyAsyncConfig, SQLAlchemyPlugin
from litestar.plugins.sqlalchemy import SQLAlchemyAsyncConfig, SQLAlchemyPlugin

if TYPE_CHECKING:
from typing import List

from sqlalchemy.ext.asyncio import AsyncSession


Expand All @@ -24,18 +22,14 @@ class TodoItem(Base):


@post("/")
async def add_item(data: TodoItem, db_session: AsyncSession) -> List[TodoItem]:
async def add_item(data: TodoItem, db_session: AsyncSession) -> Sequence[TodoItem]:
async with db_session.begin():
db_session.add(data)
return (await db_session.execute(select(TodoItem))).scalars().all()


async def init_db(app: Litestar) -> None:
async with app.state.db_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)


config = SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///todo_async.sqlite")
config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///todo_async.sqlite", create_all=True, metadata=Base.metadata
)
plugin = SQLAlchemyPlugin(config=config)
app = Litestar(route_handlers=[add_item], plugins=[plugin], on_startup=[init_db])
app = Litestar(route_handlers=[add_item], plugins=[plugin])
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.dto import SQLAlchemyDTO
from litestar.plugins.sqlalchemy import SQLAlchemyDTO

if TYPE_CHECKING:
from typing import List
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin
from litestar.plugins.sqlalchemy import SQLAlchemySerializationPlugin

if TYPE_CHECKING:
from typing import List
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin
from litestar.dto import dto_field
from litestar.plugins.sqlalchemy import SQLAlchemySerializationPlugin

if TYPE_CHECKING:
from typing import List
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from __future__ import annotations

from litestar import Litestar
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyInitPlugin, SQLAlchemySyncConfig
from litestar.contrib.sqlalchemy.plugins.init.config.sync import autocommit_before_send_handler
from litestar.plugins.sqlalchemy import SQLAlchemyInitPlugin, SQLAlchemySyncConfig, sync_autocommit_before_send_handler

config = SQLAlchemySyncConfig(
connection_string="sqlite:///:memory:",
before_send_handler=autocommit_before_send_handler,
before_send_handler=sync_autocommit_before_send_handler,
)
plugin = SQLAlchemyInitPlugin(config=config)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from sqlalchemy import select

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyInitPlugin, SQLAlchemySyncConfig
from litestar.plugins.sqlalchemy import SQLAlchemyInitPlugin, SQLAlchemySyncConfig

if TYPE_CHECKING:
from typing import Tuple
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyInitPlugin, SQLAlchemySyncConfig
from litestar.plugins.sqlalchemy import SQLAlchemyInitPlugin, SQLAlchemySyncConfig

if TYPE_CHECKING:
from typing import Any, Dict, List
Expand Down Expand Up @@ -38,8 +38,8 @@ def add_item(data: Dict[str, Any], db_session: Session) -> List[Dict[str, Any]]:


def init_db(app: Litestar) -> None:
Base.metadata.drop_all(app.state.db_engine)
Base.metadata.create_all(app.state.db_engine)
with config.get_engine().begin() as conn:
Base.metadata.create_all(conn)


config = SQLAlchemySyncConfig(connection_string="sqlite:///todo_sync.sqlite")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Sequence

from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemyPlugin, SQLAlchemySyncConfig
from litestar.plugins.sqlalchemy import SQLAlchemyPlugin, SQLAlchemySyncConfig

if TYPE_CHECKING:
from typing import List

from sqlalchemy.orm import Session


Expand All @@ -24,17 +22,12 @@ class TodoItem(Base):


@post("/", sync_to_thread=True)
def add_item(data: TodoItem, db_session: Session) -> List[TodoItem]:
def add_item(data: TodoItem, db_session: Session) -> Sequence[TodoItem]:
with db_session.begin():
db_session.add(data)
return db_session.execute(select(TodoItem)).scalars().all()


def init_db(app: Litestar) -> None:
Base.metadata.drop_all(app.state.db_engine)
Base.metadata.create_all(app.state.db_engine)


config = SQLAlchemySyncConfig(connection_string="sqlite:///todo_sync.sqlite")
config = SQLAlchemySyncConfig(connection_string="sqlite:///todo_sync.sqlite", create_all=True, metadata=Base.metadata)
plugin = SQLAlchemyPlugin(config=config)
app = Litestar(route_handlers=[add_item], plugins=[plugin], on_startup=[init_db])
app = Litestar(route_handlers=[add_item], plugins=[plugin])
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin
from litestar.plugins.sqlalchemy import SQLAlchemySerializationPlugin

if TYPE_CHECKING:
from typing import List
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from litestar import Litestar, post
from litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin
from litestar.dto import dto_field
from litestar.plugins.sqlalchemy import SQLAlchemySerializationPlugin

if TYPE_CHECKING:
from typing import List
Expand Down
8 changes: 4 additions & 4 deletions docs/usage/databases/sqlalchemy/plugins/sqlalchemy_plugin.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ We create a function ``init_db`` that we'll use to initialize the database when
.. literalinclude:: /examples/contrib/sqlalchemy/plugins/sqlalchemy_async_plugin_example.py
:caption: SQLAlchemy Async Plugin Example
:language: python
:lines: 8,32-37
:lines: 9,31-35

.. tab-item:: Sync

.. literalinclude:: /examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_plugin_example.py
:caption: SQLAlchemy Sync Plugin Example
:language: python
:lines: 8,32-36
:lines: 9,31-33

Setting Up the Plugin and the App
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -122,14 +122,14 @@ Finally, we set up the SQLAlchemy Plugin and the Litestar app.
.. literalinclude:: /examples/contrib/sqlalchemy/plugins/sqlalchemy_async_plugin_example.py
:caption: SQLAlchemy Async Plugin Example
:language: python
:lines: 8-9,38-41
:lines: 8,31-35

.. tab-item:: Sync

.. literalinclude:: /examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_plugin_example.py
:caption: SQLAlchemy Sync Plugin Example
:language: python
:lines: 8-9,37-40
:lines: 9,31-33

This configures the app with the plugin, sets up a route handler for adding items, and specifies that the ``init_db``
function should be run when the app starts up.
Expand Down
77 changes: 71 additions & 6 deletions litestar/plugins/sqlalchemy.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,75 @@
from __future__ import annotations

from advanced_alchemy.extensions.litestar import (
AlembicAsyncConfig,
AlembicCommands,
AlembicSyncConfig,
AsyncSessionConfig,
EngineConfig,
SQLAlchemyAsyncConfig,
SQLAlchemyDTO,
SQLAlchemyDTOConfig,
SQLAlchemyInitPlugin,
SQLAlchemyPlugin,
SQLAlchemySerializationPlugin,
SQLAlchemySyncConfig,
SyncSessionConfig,
async_autocommit_before_send_handler,
async_autocommit_handler_maker,
async_default_before_send_handler,
async_default_handler_maker,
base,
exceptions,
filters,
mixins,
operations,
repository,
service,
sync_autocommit_before_send_handler,
sync_autocommit_handler_maker,
sync_default_before_send_handler,
sync_default_handler_maker,
types,
utils,
)

from litestar.utils import warn_deprecation

__all__ = (
"filters",
"utils",
"operations",
"base",
"types",
"repository",
"service",
"mixins",
"exceptions",
"async_autocommit_handler_maker",
"sync_autocommit_handler_maker",
"async_default_handler_maker",
"sync_default_handler_maker",
"sync_autocommit_before_send_handler",
"async_autocommit_before_send_handler",
"sync_default_before_send_handler",
"async_default_before_send_handler",
"AlembicCommands",
"AlembicAsyncConfig",
"AlembicSyncConfig",
"AsyncSessionConfig",
"SyncSessionConfig",
"SQLAlchemyDTO",
"SQLAlchemyDTOConfig",
"SQLAlchemyAsyncConfig",
"SQLAlchemyInitPlugin",
"SQLAlchemyPlugin",
"SQLAlchemySerializationPlugin",
"SQLAlchemySyncConfig",
"EngineConfig",
)

def __getattr__(attr_name: str) -> object:
from advanced_alchemy.extensions import litestar as aa # pyright: ignore[reportMissingImports]

def __getattr__(attr_name: str) -> object:
if attr_name in {
"AuditColumns",
"BigIntAuditBase",
Expand All @@ -23,9 +89,8 @@ def __getattr__(attr_name: str) -> object:
info=f"importing {attr_name} from 'litestar.plugins.sqlalchemy' is deprecated, please"
f"import it from 'litestar.plugins.sqlalchemy.base.{attr_name}' instead",
)
value = globals()[attr_name] = getattr(aa.base, attr_name)
return value
if attr_name in aa.__all__:
value = globals()[attr_name] = getattr(aa, attr_name)
value = globals()[attr_name] = getattr(base, attr_name)
return value
if attr_name in __all__:
return getattr(attr_name, attr_name)
raise AttributeError(f"module {__name__!r} has no attribute {attr_name!r}")
Loading

0 comments on commit b3cf2fd

Please sign in to comment.