From a86bb988cd8a26bc58ff318031fc02494afa9749 Mon Sep 17 00:00:00 2001 From: smart-data-models Date: Thu, 3 Sep 2026 00:52:13 +0200 Subject: [PATCH] fix(sql-schema): stop generating a duplicate "id" column generate_sql_schema() appended a column for "id" twice in every generated schema: once via the main type-mapping branches (since an id property almost always declares its own "type", e.g. "string"), and again via the unconditional `if key == "id":` block at the end of the loop, which always fires regardless of what happened above. The result was an invalid CREATE TABLE statement declaring the same column twice in effectively every generated schema.sql. Moved the id special-case to the top of the loop with a `continue`, so it's handled exactly once and always as TEXT PRIMARY KEY, matching the original intent (id's own declared "type"/"format" was already being discarded in favor of TEXT PRIMARY KEY -- this just stops it from also being appended as a second column first). Verified against AirQualityObserved (the model from #87): "id" appears exactly once, correctly typed. Re-ran against all 231 real model.yaml files available locally: no exceptions, and exactly one "id" column per entity that declares an id property (3 entities in the set don't declare one at all, correctly unaffected). Co-Authored-By: Claude Sonnet 5 --- .../pysmartdatamodels/pysmartdatamodels.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/pysmartdatamodels/pysmartdatamodels/pysmartdatamodels.py b/pysmartdatamodels/pysmartdatamodels/pysmartdatamodels.py index 6e08d535ae..68a68c794f 100644 --- a/pysmartdatamodels/pysmartdatamodels/pysmartdatamodels.py +++ b/pysmartdatamodels/pysmartdatamodels/pysmartdatamodels.py @@ -1177,6 +1177,16 @@ def generate_sql_schema(model_yaml: str) -> str: table_create_statement = f"CREATE TABLE {entity} (" for key, value in model_yaml[entity]["properties"].items(): + # "id" always maps to the primary key column, regardless of what + # "type"/"format"/etc. it declares -- handle it here and move on, so + # it isn't *also* appended by the type-mapping branches below (that + # produced a duplicate "id" column in every generated schema, since + # id properties almost always declare a "type"). + if key == "id": + field_type = "TEXT PRIMARY KEY" + sql_schema_statements.append(f"\"{key}\" {field_type}") + continue + field_type = "JSON" # Default to JSON if type is not defined # Field type mapping @@ -1226,11 +1236,6 @@ def generate_sql_schema(model_yaml: str) -> str: sub_field_type = type_mapping.get(sub_value["type"]) sql_schema_statements.append(f"\"{sub_key}\" {sub_field_type}") - if key == "id": - field_type = "TEXT PRIMARY KEY" - # add attribute to the SQL schema statement - sql_schema_statements.append(f"\"{key}\" {field_type}") - # Complete the CREATE TABLE statement table_create_statement += ", ".join(sql_schema_statements) table_create_statement += ");"