Skip to content

1.4 — Support primary-key-less egon-data tables in import_tables_from_oep #669

Description

@joda9
  • File: edisgo/tools/config.pyConfig.import_tables_from_oep,
    local-DB branch (~line 288)
  • Branch: fix/import-tables-pkless

Problem. The local-DB branch builds an ORM class per reflected table;
SQLAlchemy ORM needs a primary key. PK-less egon-data fact tables (e.g.
demand.egon_daily_heat_demand_per_climate_zone) raise
ArgumentError: … could not assemble any primary key columns.

@@ class Config.import_tables_from_oep   (local-DB / non-OEP branch)
                 # dynamisch eine ORM-Klasse erzeugen
+                class_attrs = {"__tablename__": table_name, "__table__": table}
+                # Many egon_data fact tables have no primary key, but the
+                # SQLAlchemy ORM requires one to map a class. For these
+                # read-only reflections, synthesize a composite key from all
+                # columns so the mapping succeeds (queries read the SQL
+                # statement, not the ORM identity map).
+                if len(table.primary_key.columns) == 0:
+                    class_attrs["__mapper_args__"] = {
+                        "primary_key": list(table.columns)
+                    }
                 orm_class = type(
                     table_name,
                     (Base,),
-                    {"__tablename__": table_name, "__table__": table},
+                    class_attrs,
                 )
                 orm_classes.append(orm_class)

Verify. Reflecting a PK-less egon-data table no longer raises; the query
returns rows.

Part of #665.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions