From 287092d7bd081fc48a689d563425760b7eb4e7dc Mon Sep 17 00:00:00 2001 From: Callum Dickinson Date: Mon, 5 Aug 2024 18:21:28 +1200 Subject: [PATCH] Switch Metric-Resource relationship to back_populates Replace usage of the deprecated backref option [1] and implicit relationship population, with the new back_populates [2] option and explicit relationship definitions on both the Metric and Resource classes. This eliminates "AttributeError: type object 'Metric' has no attribute 'resource'" exceptions that can occur when Metric.resource is referenced using sqlalchemy.orm.joinedload in queries. This change is backwards compatible with SQLAlchemy 1.4. 1: https://docs.sqlalchemy.org/en/20/orm/backref.html 2: https://docs.sqlalchemy.org/en/20/orm/basic_relationships.html --- gnocchi/indexer/sqlalchemy_base.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/gnocchi/indexer/sqlalchemy_base.py b/gnocchi/indexer/sqlalchemy_base.py index 7880b5555..b62f44f6d 100644 --- a/gnocchi/indexer/sqlalchemy_base.py +++ b/gnocchi/indexer/sqlalchemy_base.py @@ -100,7 +100,8 @@ class Metric(Base, GnocchiBase, indexer.Metric): sqlalchemy.ForeignKey('resource.id', ondelete="SET NULL", name="fk_metric_resource_id_resource_id")) - + resource = sqlalchemy.orm.relationship("Resource", + back_populates="metrics") name = sqlalchemy.Column(sqlalchemy.String(255)) unit = sqlalchemy.Column(sqlalchemy.String(31)) status = sqlalchemy.Column(sqlalchemy.Enum('active', 'delete', @@ -273,7 +274,7 @@ class Resource(ResourceMixin, Base, GnocchiBase): primary_key=True) revision_end = None metrics = sqlalchemy.orm.relationship( - Metric, backref="resource", + Metric, back_populates="resource", primaryjoin="and_(Resource.id == Metric.resource_id, " "Metric.status == 'active')")