Skip to content

added support for sqlalchemy2 #120

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
merged 9 commits into from
Feb 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion devtools/prettier.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@

cache = lru_cache()

try:
from sqlalchemy import inspect as sa_inspect # type: ignore
except ImportError:
sa_inspect = None

__all__ = 'PrettyFormat', 'pformat', 'pprint'
MYPY = False
if MYPY:
Expand Down Expand Up @@ -239,8 +244,14 @@ def _format_dataclass(self, value: 'Any', _: str, indent_current: int, indent_ne
self._format_fields(value, value.__dict__.items(), indent_current, indent_new)

def _format_sqlalchemy_class(self, value: 'Any', _: str, indent_current: int, indent_new: int) -> None:
if sa_inspect is not None:
state = sa_inspect(value)
deferred = state.unloaded
else:
deferred = set()

fields = [
(field, getattr(value, field))
(field, getattr(value, field) if field not in deferred else "<deferred>")
for field in dir(value)
if not (field.startswith('_') or field in ['metadata', 'registry'])
]
Expand Down
12 changes: 11 additions & 1 deletion devtools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,23 @@ class DataClassType(metaclass=MetaDataClassType):

class MetaSQLAlchemyClassType(type):
def __instancecheck__(self, instance: 'Any') -> bool:
try:
from sqlalchemy.orm import DeclarativeBase # type: ignore
except ImportError:
pass
else:
if isinstance(instance, DeclarativeBase):
return True

try:
from sqlalchemy.ext.declarative import DeclarativeMeta # type: ignore
except ImportError:
return False
pass
else:
return isinstance(instance.__class__, DeclarativeMeta)

return False


class SQLAlchemyClassType(metaclass=MetaSQLAlchemyClassType):
pass
6 changes: 5 additions & 1 deletion tests/test_prettier.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@

try:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
try:
from sqlalchemy.orm import declarative_base
except ImportError:
from sqlalchemy.ext.declarative import declarative_base

SQLAlchemyBase = declarative_base()
except ImportError:
SQLAlchemyBase = None
Expand Down