From 336927062dfccbfc5913862adbccf2c133dcc783 Mon Sep 17 00:00:00 2001 From: godara-alt Date: Wed, 25 Nov 2026 07:21:57 -0600 Subject: [PATCH 1/3] fix(declare): reject constant defaults on primary key attributes (#1712) Permit generated CURRENT_TIMESTAMP defaults, preserve secondary defaults, and test declarations across MySQL and PostgreSQL adapters. --- src/datajoint/declare.py | 8 ++++ tests/unit/test_primary_key_defaults.py | 53 +++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 tests/unit/test_primary_key_defaults.py diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index a796e669b..4dd3659fd 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -1247,6 +1247,14 @@ def compile_attribute( default_val = match["default"] base_val = default_val.split("(")[0].upper() + # Key values must be supplied or generated on insertion, not copied + # from a constant default that would give multiple rows the same key. + if in_key and base_val != "CURRENT_TIMESTAMP": + raise DataJointError( + f"Primary key attribute {match['name']!r} cannot have a constant default. " + "Remove the default from its declaration." + ) + if base_val in CONSTANT_LITERALS: # SQL constants like NULL, CURRENT_TIMESTAMP - use as-is match["default"] = f"NOT NULL DEFAULT {default_val}" diff --git a/tests/unit/test_primary_key_defaults.py b/tests/unit/test_primary_key_defaults.py new file mode 100644 index 000000000..354ad7d68 --- /dev/null +++ b/tests/unit/test_primary_key_defaults.py @@ -0,0 +1,53 @@ +"""A primary key cannot silently take a constant default (#1712).""" + +import pytest + +from datajoint.adapters import MySQLAdapter, PostgreSQLAdapter +from datajoint.declare import compile_attribute, prepare_declare +from datajoint.errors import DataJointError + + +@pytest.mark.parametrize("adapter_type", [MySQLAdapter, PostgreSQLAdapter], ids=["mysql", "postgresql"]) +@pytest.mark.parametrize( + "line", + [ + "probe_id = 1 : int32", + "probe_id = 'fixed' : varchar(16)", + 'probe_id = "fixed" : varchar(16)', + ], +) +def test_constant_primary_key_defaults_are_rejected(adapter_type, line): + """Reject constants during declaration, before touching a database.""" + with pytest.raises(DataJointError, match=r"Primary key attribute 'probe_id'.*constant default"): + prepare_declare(f"{line}\n---\nlabel : varchar(16)", {}, adapter_type()) + + +@pytest.mark.parametrize("adapter_type", [MySQLAdapter, PostgreSQLAdapter], ids=["mysql", "postgresql"]) +@pytest.mark.parametrize("default", ["CURRENT_TIMESTAMP", "current_timestamp", "CURRENT_TIMESTAMP(3)"]) +def test_generated_timestamp_default_is_allowed_on_key(adapter_type, default): + """CURRENT_TIMESTAMP is generated per insert, unlike a fixed literal.""" + name, sql, _store, _comment = compile_attribute( + f"visit_ts = {default} : datetime", in_key=True, foreign_key_sql=[], context={}, adapter=adapter_type() + ) + assert name == "visit_ts" + assert "DEFAULT " in sql + assert default in sql + + +@pytest.mark.parametrize("adapter_type", [MySQLAdapter, PostgreSQLAdapter], ids=["mysql", "postgresql"]) +def test_primary_key_without_default_is_unchanged(adapter_type): + name, sql, _store, _comment = compile_attribute( + "probe_id : int32", in_key=True, foreign_key_sql=[], context={}, adapter=adapter_type() + ) + assert name == "probe_id" + assert "DEFAULT" not in sql + + +@pytest.mark.parametrize("adapter_type", [MySQLAdapter, PostgreSQLAdapter], ids=["mysql", "postgresql"]) +@pytest.mark.parametrize("default", ["1", "'fixed'"]) +def test_secondary_attribute_constant_defaults_are_unchanged(adapter_type, default): + name, sql, _store, _comment = compile_attribute( + f"label = {default} : varchar(16)", in_key=False, foreign_key_sql=[], context={}, adapter=adapter_type() + ) + assert name == "label" + assert "DEFAULT " in sql From 438c1bd30514f195cb50be691c6fe3783ee0931c Mon Sep 17 00:00:00 2001 From: godara-alt Date: Wed, 25 Nov 2026 08:06:31 -0600 Subject: [PATCH 2/3] fix(declare): preserve generated singleton keys and update university test fixture Allow the platform-created singleton sentinel its fixed default without exposing that exception to user declarations. Remove a redundant constant key default from the university fixture, whose CSV supplies an explicit key. Add regression tests. --- src/datajoint/declare.py | 17 ++++++++++++----- tests/schema_university.py | 2 +- tests/unit/test_primary_key_defaults.py | 23 +++++++++++++++++++++++ 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 4dd3659fd..c1f8f5f5a 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -642,8 +642,10 @@ def prepare_declare( column_comments = {} # column_name -> comment (for PostgreSQL COMMENT ON) fk_index_candidates = [] # PostgreSQL: FK column-lists that may need a support index (#1512) - def add_attribute(line: str, in_key: bool) -> None: - name, sql, store, comment = compile_attribute(line, in_key, foreign_key_sql, context, adapter) + def add_attribute(line: str, in_key: bool, *, platform_singleton: bool = False) -> None: + name, sql, store, comment = compile_attribute( + line, in_key, foreign_key_sql, context, adapter, platform_singleton=platform_singleton + ) if store: external_stores.append(store) if in_key and name not in primary_key: @@ -693,7 +695,8 @@ def add_attribute(line: str, in_key: bool) -> None: # what makes it hold at most one row. Only the parse knows whether it does: # `index (...)` contributes no attribute and `-> Parent` may contribute many. if not primary_key: - add_attribute(SINGLETON_DEFINITION, True) + # This sentinel is framework-generated, never a user declaration. + add_attribute(SINGLETON_DEFINITION, True, platform_singleton=True) for line in _tier_attributes(table_name, config): add_attribute(line, False) @@ -1191,7 +1194,7 @@ def substitute_special_type(match: dict, category: str, foreign_key_sql: list[st def compile_attribute( - line: str, in_key: bool, foreign_key_sql: list[str], context: dict, adapter + line: str, in_key: bool, foreign_key_sql: list[str], context: dict, adapter, *, platform_singleton: bool = False ) -> tuple[str, str, str | None, str | None]: """ Convert an attribute definition from DataJoint format to SQL. @@ -1208,6 +1211,8 @@ def compile_attribute( Namespace for codec lookup. adapter : DatabaseAdapter Database adapter for backend-specific SQL generation. + platform_singleton : bool, optional + Allow the framework-generated singleton key's fixed default; never set for user attributes. Returns ------- @@ -1249,7 +1254,9 @@ def compile_attribute( # Key values must be supplied or generated on insertion, not copied # from a constant default that would give multiple rows the same key. - if in_key and base_val != "CURRENT_TIMESTAMP": + if in_key and base_val != "CURRENT_TIMESTAMP" and not ( + platform_singleton and line == SINGLETON_DEFINITION + ): raise DataJointError( f"Primary key attribute {match['name']!r} cannot have a constant default. " "Remove the default from its declaration." diff --git a/tests/schema_university.py b/tests/schema_university.py index e07951282..02c08f084 100644 --- a/tests/schema_university.py +++ b/tests/schema_university.py @@ -67,7 +67,7 @@ class Section(dj.Manual): class CurrentTerm(dj.Manual): definition = """ - omega=0 : tinyint + omega : tinyint --- -> Term """ diff --git a/tests/unit/test_primary_key_defaults.py b/tests/unit/test_primary_key_defaults.py index 354ad7d68..9d4e65b51 100644 --- a/tests/unit/test_primary_key_defaults.py +++ b/tests/unit/test_primary_key_defaults.py @@ -51,3 +51,26 @@ def test_secondary_attribute_constant_defaults_are_unchanged(adapter_type, defau ) assert name == "label" assert "DEFAULT " in sql + + +@pytest.mark.parametrize("adapter_type", [MySQLAdapter, PostgreSQLAdapter], ids=["mysql", "postgresql"]) +def test_framework_generated_singleton_still_uses_its_sentinel_default(adapter_type): + """The internal zero-key singleton must still compile to a single-row table.""" + _comment, primary_key, attribute_sql, *_rest = prepare_declare( + "---\nlabel : varchar(16)", {}, adapter_type() + ) + assert primary_key == ["_singleton"] + assert any("_singleton" in sql and "DEFAULT " in sql for sql in attribute_sql) + + +@pytest.mark.parametrize("adapter_type", [MySQLAdapter, PostgreSQLAdapter], ids=["mysql", "postgresql"]) +def test_singleton_literal_is_not_exempt_outside_framework_path(adapter_type): + """The exception must not silently exempt callers of compile_attribute.""" + with pytest.raises(DataJointError, match=r"Primary key attribute '_singleton'.*constant default"): + compile_attribute( + "_singleton = 1 : bool # singleton primary key", + in_key=True, + foreign_key_sql=[], + context={}, + adapter=adapter_type(), + ) From b43425beb2c6ef0c94627708c1602bb96eec8fb5 Mon Sep 17 00:00:00 2001 From: godara-alt Date: Wed, 25 Nov 2026 08:07:53 -0600 Subject: [PATCH 3/3] style: apply ruff-format to PK default checks and tests --- src/datajoint/declare.py | 4 +--- tests/unit/test_primary_key_defaults.py | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index c1f8f5f5a..f7e2d9056 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -1254,9 +1254,7 @@ def compile_attribute( # Key values must be supplied or generated on insertion, not copied # from a constant default that would give multiple rows the same key. - if in_key and base_val != "CURRENT_TIMESTAMP" and not ( - platform_singleton and line == SINGLETON_DEFINITION - ): + if in_key and base_val != "CURRENT_TIMESTAMP" and not (platform_singleton and line == SINGLETON_DEFINITION): raise DataJointError( f"Primary key attribute {match['name']!r} cannot have a constant default. " "Remove the default from its declaration." diff --git a/tests/unit/test_primary_key_defaults.py b/tests/unit/test_primary_key_defaults.py index 9d4e65b51..f0b4711e4 100644 --- a/tests/unit/test_primary_key_defaults.py +++ b/tests/unit/test_primary_key_defaults.py @@ -56,9 +56,7 @@ def test_secondary_attribute_constant_defaults_are_unchanged(adapter_type, defau @pytest.mark.parametrize("adapter_type", [MySQLAdapter, PostgreSQLAdapter], ids=["mysql", "postgresql"]) def test_framework_generated_singleton_still_uses_its_sentinel_default(adapter_type): """The internal zero-key singleton must still compile to a single-row table.""" - _comment, primary_key, attribute_sql, *_rest = prepare_declare( - "---\nlabel : varchar(16)", {}, adapter_type() - ) + _comment, primary_key, attribute_sql, *_rest = prepare_declare("---\nlabel : varchar(16)", {}, adapter_type()) assert primary_key == ["_singleton"] assert any("_singleton" in sql and "DEFAULT " in sql for sql in attribute_sql)