columns should be a property of the Entity object

This commit is contained in:
Fabio Manganiello 2022-04-05 23:04:19 +02:00
parent 8a70f1d38e
commit fe0f3202fe
Signed by untrusted user: blacklight
GPG key ID: D90FBA7F76362774
2 changed files with 20 additions and 6 deletions

View file

@ -1,11 +1,20 @@
import inspect import inspect
import pathlib import pathlib
from datetime import datetime from datetime import datetime
from typing import Mapping, Type from typing import Mapping, Type, Tuple
import pkgutil import pkgutil
from sqlalchemy import Column, Index, Integer, String, DateTime, JSON, UniqueConstraint from sqlalchemy import (
from sqlalchemy.orm import declarative_base Column,
Index,
Integer,
String,
DateTime,
JSON,
UniqueConstraint,
inspect as schema_inspect,
)
from sqlalchemy.orm import declarative_base, ColumnProperty
Base = declarative_base() Base = declarative_base()
entities_registry: Mapping[Type['Entity'], Mapping] = {} entities_registry: Mapping[Type['Entity'], Mapping] = {}
@ -40,6 +49,12 @@ class Entity(Base):
'polymorphic_on': type, 'polymorphic_on': type,
} }
@classmethod
@property
def columns(cls) -> Tuple[ColumnProperty]:
inspector = schema_inspect(cls)
return tuple(inspector.mapper.column_attrs)
def _discover_entity_types(): def _discover_entity_types():
from platypush.context import get_plugin from platypush.context import get_plugin

View file

@ -4,7 +4,7 @@ from threading import Thread, Event
from time import time from time import time
from typing import Iterable, List from typing import Iterable, List
from sqlalchemy import and_, or_, inspect as schema_inspect from sqlalchemy import and_, or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ._base import Entity from ._base import Entity
@ -93,8 +93,7 @@ class EntitiesEngine(Thread):
self, entities: List[Entity], existing_entities: List[Entity] self, entities: List[Entity], existing_entities: List[Entity]
) -> List[Entity]: ) -> List[Entity]:
def merge(entity: Entity, existing_entity: Entity) -> Entity: def merge(entity: Entity, existing_entity: Entity) -> Entity:
inspector = schema_inspect(entity.__class__) columns = [col.key for col in entity.columns]
columns = [col.key for col in inspector.mapper.column_attrs]
for col in columns: for col in columns:
if col not in ('id', 'created_at'): if col not in ('id', 'created_at'):
setattr(existing_entity, col, getattr(entity, col)) setattr(existing_entity, col, getattr(entity, col))