diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index a796e669b..f7e2d9056 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 ------- @@ -1247,6 +1252,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" 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." + ) + 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/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 new file mode 100644 index 000000000..f0b4711e4 --- /dev/null +++ b/tests/unit/test_primary_key_defaults.py @@ -0,0 +1,74 @@ +"""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 + + +@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(), + )