Skip to content
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

add_to_dict(): Fix mapping of to_dict() #325

Merged
merged 3 commits into from
Dec 10, 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
3 changes: 3 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ $ pip install --user --upgrade --pre unihan-db

### Bug fixes

- SQLAlchemy: Fix `add_to_dict()` event mapper bug (#325)

This allows `Unhn` rows to use `row.as_dict()` once more.
- Bump unihan-etl 0.30.0post0 -> 0.30.1

Fix `kRSUnicode` double apostrophes.
Expand Down
2 changes: 2 additions & 0 deletions examples/01_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@
random_row = random_row_query.first()

pprint.pprint(bootstrap.to_dict(random_row))

pprint.pprint(random_row.to_dict()) # type:ignore
9 changes: 7 additions & 2 deletions src/unihan_db/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import sqlalchemy
from sqlalchemy import create_engine, event
from sqlalchemy.orm import Session, class_mapper, scoped_session, sessionmaker
from sqlalchemy.orm import Mapper, Session, class_mapper, scoped_session, sessionmaker
from sqlalchemy.orm.decl_api import registry
from sqlalchemy.orm.scoping import ScopedSession

Expand Down Expand Up @@ -198,6 +198,12 @@ def bootstrap_unihan(
log.info("Done adding rows.")


@event.listens_for(Unhn, "before_mapper_configured", once=True)
def setup_orm_mappings(mapper: Mapper[Base], class_: Base) -> None:
"""Add special methods to Base declarative model used in Unihan DB."""
add_to_dict(class_) # Add .to_dict() to rows returned


def to_dict(obj: t.Any, found: t.Optional[t.Set[t.Any]] = None) -> t.Dict[str, object]:
"""Return dictionary of an SQLAlchemy Query result.

Expand Down Expand Up @@ -272,7 +278,6 @@ def get_session(
engine_url = engine_url.format(**{"user_data_dir": dirs.user_data_dir})
engine = create_engine(engine_url)

event.listen(mapper_reg, "after_configured", add_to_dict(Base))
Base.metadata.create_all(bind=engine)
session_factory = sessionmaker(bind=engine)
session = scoped_session(session_factory)
Expand Down