Skip to content

Commit

Permalink
feat: updated advanced_alchemy.base reference docs (#327)
Browse files Browse the repository at this point in the history
* feat: docs updates

* chore: ruff updates
  • Loading branch information
cofin authored Jan 9, 2025
1 parent d59a52e commit 53d32c1
Show file tree
Hide file tree
Showing 10 changed files with 300 additions and 192 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ repos:
- id: unasyncd
additional_dependencies: ["ruff"]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.8.6"
rev: "v0.9.0"
hooks:
# Run the linter.
- id: ruff
Expand Down
58 changes: 41 additions & 17 deletions advanced_alchemy/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,16 +163,15 @@ def __getattr__(attr_name: str) -> object:
def merge_table_arguments(cls: type[DeclarativeBase], table_args: TableArgsType | None = None) -> TableArgsType:
"""Merge Table Arguments.
When using mixins that include their own table args, it is difficult to append info into the model such as a comment.
This function helps you merge the args together.
This function helps merge table arguments when using mixins that include their own table args,
making it easier to append additional information such as comments or constraints to the model.
Args:
cls: :class:`sqlalchemy.orm.DeclarativeBase` This is the model that will get the table args
table_args: :class:`TableArgsType` additional information to add to table_args
cls (type[:class:`sqlalchemy.orm.DeclarativeBase`]): The model that will get the table args.
table_args (:class:`TableArgsType`, optional): Additional information to add to table_args.
Returns:
:class:`TableArgsType`
:class:`TableArgsType`: Merged table arguments.
"""
args: list[Any] = []
kwargs: dict[str, Any] = {}
Expand Down Expand Up @@ -200,7 +199,13 @@ def merge_table_arguments(cls: type[DeclarativeBase], table_args: TableArgsType

@runtime_checkable
class ModelProtocol(Protocol):
"""The base SQLAlchemy model protocol."""
"""The base SQLAlchemy model protocol.
Attributes:
__table__ (:class:`sqlalchemy.sql.FromClause`): The table associated with the model.
__mapper__ (:class:`sqlalchemy.orm.Mapper`): The mapper for the model.
__name__ (str): The name of the model.
"""

if TYPE_CHECKING:
__table__: FromClause
Expand All @@ -217,7 +222,13 @@ def to_dict(self, exclude: set[str] | None = None) -> dict[str, Any]:


class BasicAttributes:
"""Basic attributes for SQLALchemy tables and queries."""
"""Basic attributes for SQLAlchemy tables and queries.
Provides a method to convert the model to a dictionary representation.
Methods:
to_dict: Converts the model to a dictionary, excluding specified fields. :no-index:
"""

if TYPE_CHECKING:
__name__: str
Expand All @@ -239,10 +250,12 @@ def to_dict(self, exclude: set[str] | None = None) -> dict[str, Any]:


class CommonTableAttributes(BasicAttributes):
"""Common attributes for SQLALchemy tables.
"""Common attributes for SQLAlchemy tables.
.. seealso::
:class:`BasicAttributes`
Inherits from :class:`BasicAttributes` and provides a mechanism to infer table names from class names.
Attributes:
__tablename__ (str): The inferred table name.
"""

if TYPE_CHECKING:
Expand All @@ -262,10 +275,10 @@ def create_registry(
"""Create a new SQLAlchemy registry.
Args:
custom_annotation_map: :class:`dict` of custom type annotations to use for the registry
custom_annotation_map (dict, optional): Custom type annotations to use for the registry.
Returns:
:class:`sqlalchemy.orm.registry`
:class:`sqlalchemy.orm.registry`: A new SQLAlchemy registry with the specified type annotations.
"""
import uuid as core_uuid

Expand Down Expand Up @@ -305,7 +318,14 @@ def create_registry(


class MetadataRegistry:
"""A registry for metadata."""
"""A registry for metadata.
Provides methods to get and set metadata for different bind keys.
Methods:
get: Retrieves the metadata for a given bind key.
set: Sets the metadata for a given bind key.
"""

_instance: MetadataRegistry | None = None
_registry: dict[str | None, MetaData] = {None: orm_registry.metadata}
Expand Down Expand Up @@ -342,8 +362,12 @@ def __contains__(self, bind_key: str | None) -> bool:
class AdvancedDeclarativeBase(DeclarativeBase):
"""A subclass of declarative base that allows for overriding of the registry.
.. seealso::
:class:`sqlalchemy.orm.DeclarativeBase`
Inherits from :class:`sqlalchemy.orm.DeclarativeBase`.
Attributes:
registry (:class:`sqlalchemy.orm.registry`): The registry for the declarative base.
__metadata_registry__ (:class:`~advanced_alchemy.base.MetadataRegistry`): The metadata registry.
__bind_key__ (Optional[:class:`str`]): The bind key for the metadata.
"""

registry = orm_registry
Expand All @@ -364,8 +388,8 @@ class UUIDBase(_UUIDPrimaryKey, CommonTableAttributes, AdvancedDeclarativeBase,
"""Base for all SQLAlchemy declarative models with UUID v4 primary keys.
.. seealso::
:class:`advanced_alchemy.mixins.UUIDPrimaryKey`
:class:`CommonTableAttributes`
:class:`advanced_alchemy.mixins.UUIDPrimaryKey`
:class:`AdvancedDeclarativeBase`
:class:`AsyncAttrs`
"""
Expand Down
4 changes: 2 additions & 2 deletions advanced_alchemy/config/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def engine_config_dict(self) -> dict[str, Any]:
"""Return the engine configuration as a dict.
Returns:
A string keyed dict of config kwargs for the SQLAlchemy :func:`get_engine <sqlalchemy.get_engine>`
A string keyed dict of config kwargs for the SQLAlchemy :func:`sqlalchemy.get_engine`
function.
"""
return simple_asdict(self.engine_config, exclude_empty=True)
Expand All @@ -217,7 +217,7 @@ def session_config_dict(self) -> dict[str, Any]:
"""Return the session configuration as a dict.
Returns:
A string keyed dict of config kwargs for the SQLAlchemy :class:`sessionmaker <sqlalchemy.orm.sessionmaker>`
A string keyed dict of config kwargs for the SQLAlchemy :class:`sqlalchemy.orm.sessionmaker`
class.
"""
return simple_asdict(self.session_config, exclude_empty=True)
Expand Down
78 changes: 36 additions & 42 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,11 @@
"sphinx.ext.autosectionlabel",
"sphinx.ext.githubpages",
"sphinx.ext.viewcode",
# "sphinx_autodoc_typehints",
"auto_pytabs.sphinx_ext",
"tools.sphinx_ext.missing_references",
"tools.sphinx_ext.changelog",
"sphinx_autodoc_typehints",
"myst_parser",
"auto_pytabs.sphinx_ext",
"sphinx_copybutton",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
Expand Down Expand Up @@ -134,6 +135,12 @@
"CommonTableAttributes": "advanced_alchemy.base.CommonTableAttributes",
"AuditColumns": "advanced_alchemy.base.AuditColumns",
"UUIDPrimaryKey": "advanced_alchemy.base.UUIDPrimaryKey",
"EngineConfig": "advanced_alchemy.config.EngineConfig",
"AsyncSessionConfig": "advanced_alchemy.config.AsyncSessionConfig",
"SyncSessionConfig": "advanced_alchemy.config.SyncSessionConfig",
"EmptyType": "advanced_alchemy.utils.dataclass.EmptyType",
"async_sessionmaker": "sqlalchemy.ext.asyncio.async_sessionmaker",
"sessionmaker": "sqlalchemy.orm.sessionmaker",
}
autodoc_mock_imports = [
"alembic",
Expand All @@ -143,15 +150,12 @@
"_sa.create_engine._sphinx_paramlinks_creator",
"sqlalchemy.Dialect",
"sqlalchemy.orm.MetaData",
"sqlalchemy.orm.strategy_options._AbstractLoad",
"sqlalchemy.sql.base.ExecutableOption",
"sqlalchemy.Connection.in_transaction",
"sqlalchemy.orm.attributes.InstrumentedAttribute",
"sqlalchemy.orm.decl_base._TableArgsType",
"sqlalchemy.orm.DeclarativeBase",
"litestar.dto.data_structures.DTOData",
"sqlalchemy.sql.schema._NamingSchemaParameter",
"sqlalchemy.sql.FromClause",
# Add these new entries:
"advanced_alchemy.config.engine.EngineConfig",
"advanced_alchemy.config.asyncio.AsyncSessionConfig",
"advanced_alchemy.config.sync.SyncSessionConfig",
"advanced_alchemy.utils.dataclass.EmptyType",
"advanced_alchemy.extensions.litestar.plugins.init.config.engine.EngineConfig",
]


Expand All @@ -170,7 +174,7 @@
templates_path = ["_templates"]
html_js_files = ["versioning.js"]
html_css_files = ["custom.css"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "PYPI_README.md"]
html_show_sourcelink = True
html_copy_source = True

Expand All @@ -186,15 +190,32 @@
"logo_target": "/",
"github_url": "https://github.com/litestar-org/advanced-alchemy",
"navigation_with_keys": True,
"globaltoc_expand_depth": 1,
"globaltoc_expand_depth": 2,
"light_logo": "_static/logo-default.png",
"dark_logo": "_static/logo-default.png",
"discussion_url": "https://discord.gg/dSDXd4mKhp",
"nav_links": [
{"title": "Home", "url": "index"},
{
"title": "Community",
"title": "About",
"children": [
{
"title": "Changelog",
"url": "changelog",
"summary": "All changes for Advanced Alchemy",
},
{
"title": "Litestar Organization",
"summary": "Details about the Litestar organization, the team behind Advanced Alchemy",
"url": "https://litestar.dev/about/organization",
"icon": "org",
},
{
"title": "Releases",
"summary": "Explore the release process, versioning, and deprecation policy for Advanced Alchemy",
"url": "releases",
"icon": "releases",
},
{
"title": "Contributing",
"summary": "Learn how to contribute to the Advanced Alchemy project",
Expand All @@ -213,33 +234,7 @@
"url": "https://github.com/litestar-org/.github?tab=coc-ov-file#security-ov-file",
"icon": "coc",
},
],
},
{
"title": "About",
"children": [
{
"title": "Litestar Organization",
"summary": "Details about the Litestar organization, the team behind Advanced Alchemy",
"url": "https://litestar.dev/about/organization",
"icon": "org",
},
{
"title": "Releases",
"summary": "Explore the release process, versioning, and deprecation policy for Advanced Alchemy",
"url": "releases",
"icon": "releases",
},
],
},
{
"title": "Release notes",
"children": [
{
"title": "Changelog",
"url": "changelog",
"summary": "All changes for Advanced Alchemy",
},
{"title": "Sponsor", "url": "https://github.com/sponsors/Litestar-Org", "icon": "heart"},
],
},
{
Expand All @@ -265,7 +260,6 @@
},
],
},
{"title": "Sponsor", "url": "https://github.com/sponsors/Litestar-Org", "icon": "heart"},
],
}

Expand Down
6 changes: 5 additions & 1 deletion docs/getting-started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@ offering useful and easy-to-use features for your database projects.
* `Alembic <https://alembic.sqlalchemy.org/en/latest/>`_
* `Typing Extensions <https://typing-extensions.readthedocs.io/en/latest/>`_

It works standalone or integrated with any WSGI or ASGI framework, and comes bundled with extensions for:
It's designed to work on it's own, but it equally as well when integrated with your favorite web framework.

We've built extensions for some of the most popular frameworks, so you can get the most out of Advanced Alchemy with minimal effort.

* `Litestar <https://docs.litestar.dev/>`_
* `FastAPI <https://fastapi.tiangolo.com/>`_
* `Starlette <https://www.starlette.io/>`_
* `Flask <https://flask.palletsprojects.com/>`_
* `Sanic <https://sanicframework.org/>`_

If your framework is not listed, don't worry! Advanced Alchemy is designed to be modular and easily integrated with any Python web framework. Join our discord and we'll help you get started.

Installation
------------

Expand Down
1 change: 1 addition & 0 deletions docs/reference/base.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ base
:imported-members:
:undoc-members:
:show-inheritance:
:no-index: advanced_alchemy.base.AdvancedDeclarativeBase.registry advanced_alchemy.base.BasicAttributes.to_dict
2 changes: 1 addition & 1 deletion docs/reference/mixins/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
mixins
======

API Reference for the ``mixins`` module
API Reference for the ``advanced_alchemy.mixins`` module

.. note:: Private methods and attributes are not included in the API reference.

Expand Down
2 changes: 1 addition & 1 deletion docs/usage/frameworks/litestar.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ First, configure the SQLAlchemy plugin with Litestar. The plugin handles databas
.. code-block:: python
from litestar import Litestar
from advanced_alchemy.extensions.litestar import (
from litestar.plugins.sqlalchemy import (
AsyncSessionConfig,
SQLAlchemyAsyncConfig,
SQLAlchemyPlugin,
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ doc = [
"sphinx-paramlinks>=0.6.0",
"sphinx-togglebutton>=0.3.2",
"sphinx-toolbox>=3.8.1",
"myst-parser",
"sphinx-autodoc-typehints",
]
duckdb = ["duckdb>=1.1.2", "duckdb-engine>=0.13.4", "pytz>=2024.2"]
fastapi = ["fastapi[all]>=0.115.3"]
Expand Down Expand Up @@ -273,6 +275,7 @@ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
fixable = ["ALL"]
ignore = [
"A003", # flake8-builtins - class attribute {name} is shadowing a python builtin
"A005", # flake8-builtins - module {name} shadows a Python standard-library module
"B010", # flake8-bugbear - do not call setattr with a constant attribute value
"D100", # pydocstyle - missing docstring in public module
"D101", # pydocstyle - missing docstring in public class
Expand Down
Loading

0 comments on commit 53d32c1

Please sign in to comment.