diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1aa12f52f..df85decc4 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -1005,7 +1005,10 @@ def get_indexes_sql(self, schema_name: str, table_name: str) -> str: Returns ------- str - SQL query to get index definitions. + SQL query that returns one row per column of each secondary index + (the primary key left out), with the columns ``index_name``, + ``column_name`` (NULL for an expression), ``non_unique`` (0 or 1) + and ``seq_in_index`` (1-based). ``Heading`` reads these names. """ ... diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 52686763f..7cce96246 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -1023,11 +1023,34 @@ def parse_foreign_key_error(self, error_message: str) -> dict[str, str | list[st } def get_indexes_sql(self, schema_name: str, table_name: str) -> str: - """Query to get index definitions.""" + """ + Query to get secondary indexes, one row per key column. + + Returns the same columns as the MySQL query: ``index_name``, + ``column_name``, ``non_unique`` and ``seq_in_index``, ordered by index + name and column position. The primary-key index is left out. + + An expression in an index has no column in ``pg_attribute`` (its + ``indkey`` entry is 0), so the left join gives it a NULL + ``column_name``. Heading skips such entries, as it does for MySQL's + functional key parts. Columns added with ``INCLUDE`` are not key + columns and are left out. + """ return ( - f"SELECT indexname, indexdef FROM pg_indexes " - f"WHERE schemaname = {self.quote_string(schema_name)} " - f"AND tablename = {self.quote_string(table_name)}" + f"SELECT ic.relname AS index_name, a.attname AS column_name, " + f"CASE WHEN i.indisunique THEN 0 ELSE 1 END AS non_unique, " + f"k.ord AS seq_in_index " + f"FROM pg_index i " + f"JOIN pg_class ic ON ic.oid = i.indexrelid " + f"JOIN pg_class tc ON tc.oid = i.indrelid " + f"JOIN pg_namespace ns ON ns.oid = tc.relnamespace " + f"CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) " + f"LEFT JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum " + f"WHERE ns.nspname = {self.quote_string(schema_name)} " + f"AND tc.relname = {self.quote_string(table_name)} " + f"AND NOT i.indisprimary " + f"AND k.ord <= i.indnkeyatts " + f"ORDER BY ic.relname, k.ord" ) def parse_column_info(self, row: dict[str, Any]) -> dict[str, Any]: diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 87cef4619..25ab0a447 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -1045,7 +1045,9 @@ def alter( raise NotImplementedError("table.alter cannot alter the primary key (yet).") if foreign_key_sql != foreign_key_sql_: raise NotImplementedError("table.alter cannot alter foreign keys (yet).") - if index_sql != index_sql_: + # describe() lists indexes in index-name order, and index names differ + # between backends, so compare the indexes without regard to order. + if sorted(index_sql) != sorted(index_sql_): raise NotImplementedError("table.alter cannot alter indexes (yet)") if attribute_sql != attribute_sql_: sql.extend(_make_attribute_alter(attribute_sql, attribute_sql_, primary_key, adapter, column_comments)) diff --git a/src/datajoint/heading.py b/src/datajoint/heading.py index a841bf970..111d07ab0 100644 --- a/src/datajoint/heading.py +++ b/src/datajoint/heading.py @@ -639,13 +639,16 @@ def _init_from_database(self) -> None: unique=(non_unique == 0 or not non_unique), nullable=nullable, ) + # An expression in an index has no column name. An index with any + # expression is left out: listing only its plain columns would describe + # a different index (for a unique index, a stricter constraint). self.indexes = { - tuple(item[k]["column"] for k in sorted(item.keys()) if item[k]["column"] is not None): dict( + tuple(item[k]["column"] for k in sorted(item.keys())): dict( unique=item[1]["unique"], nullable=any(v["nullable"] for v in item.values()), ) for item in keys.values() - if any(item[k]["column"] is not None for k in item.keys()) + if all(item[k]["column"] is not None for k in item.keys()) } def select(self, select_list, rename_map=None, compute_map=None): diff --git a/tests/integration/test_heading_indexes.py b/tests/integration/test_heading_indexes.py new file mode 100644 index 000000000..e1e7cf388 --- /dev/null +++ b/tests/integration/test_heading_indexes.py @@ -0,0 +1,225 @@ +""" +Secondary indexes read back from the database, on MySQL and PostgreSQL. + +``Heading.indexes`` feeds ``describe()``, and ``alter()`` compares the indexes +of the new definition with those of ``describe()``. On PostgreSQL the heading +used to find no indexes at all, so ``describe()`` dropped ``[unique]`` foreign +keys and secondary indexes, and ``alter()`` with an unchanged definition raised +``NotImplementedError`` on any table with a secondary index. +""" + +import time + +import pytest + +import datajoint as dj +from datajoint.declare import declare + +CHILD_DEFINITION = """ +child_id : int32 +--- +-> [unique] Parent +-> Other +a : int32 +b : varchar(32) +c : int32 +index(a) +unique index(b, c) +""" + +# What MySQL reports for Child: the foreign keys' indexes and the two declared ones. +EXPECTED_INDEXES = { + ("a",): {"unique": False, "nullable": False}, + ("b", "c"): {"unique": True, "nullable": False}, + ("other_id",): {"unique": False, "nullable": False}, + ("parent_id",): {"unique": True, "nullable": False}, +} + + +# What describe() returns for Child on MySQL, with runs of spaces collapsed. +EXPECTED_DESCRIBE = [ + "child_id : int32", + "---", + "-> [unique] Parent", + "-> Other", + "a : int32", + "b : varchar(32)", + "c : int32", + "INDEX (a)", + "UNIQUE INDEX (b, c)", +] + + +class Parent(dj.Manual): + definition = """ + parent_id : int32 + """ + + +class Other(dj.Manual): + definition = """ + other_id : int32 + """ + + +class Child(dj.Manual): + definition = CHILD_DEFINITION + + +class ChildCopy(dj.Manual): + definition = CHILD_DEFINITION # replaced by Child().describe() in the test + + +@pytest.fixture +def schema_indexes(connection_by_backend, db_creds_by_backend): + backend = db_creds_by_backend["backend"] + test_id = str(int(time.time() * 1000))[-8:] + schema_name = f"djtest_indexes_{backend}_{test_id}" + adapter = connection_by_backend.adapter + connection_by_backend.query(f"DROP DATABASE IF EXISTS {adapter.quote_identifier(schema_name)}") + schema = dj.Schema(schema_name, context=dict(Parent=Parent, Other=Other), connection=connection_by_backend) + schema(Parent) + schema(Other) + schema(Child) + yield schema + schema.drop(prompt=False) + + +def _context(): + return dict(Parent=Parent, Other=Other, Child=Child) + + +def _indexes(table): + """The heading's indexes, after loading the heading (it loads on first use).""" + heading = table.heading + assert heading.table_status is not None + return heading.indexes + + +def test_heading_indexes(schema_indexes): + """Both backends report the same secondary indexes, without the primary key.""" + indexes = _indexes(Child()) + assert indexes == EXPECTED_INDEXES + assert list(indexes) == list(EXPECTED_INDEXES) # ordered by index name on both + + +def test_describe_shows_indexes(schema_indexes): + """describe() keeps the [unique] foreign key and the secondary indexes.""" + definition = Child().describe(context=_context()) + assert [" ".join(line.split()) for line in definition.splitlines()] == EXPECTED_DESCRIBE + + +def test_describe_declares_same_table(schema_indexes): + """The output of describe() declares the same table as the definition.""" + child = Child() + adapter = child.connection.adapter + context = _context() + from_definition = declare(child.full_table_name, child.definition, context, adapter) + from_describe = declare(child.full_table_name, child.describe(context=context), context, adapter) + assert from_describe[0] == from_definition[0] # CREATE TABLE + assert from_describe[5] == from_definition[5] # CREATE INDEX and comments (PostgreSQL) + + +def test_redeclare_from_describe(schema_indexes): + """A table declared from describe() has the same indexes.""" + ChildCopy.definition = Child().describe(context=_context()) + try: + schema_indexes(ChildCopy, context=_context()) + assert _indexes(ChildCopy()) == EXPECTED_INDEXES + assert ChildCopy().describe(context=_context()) == Child().describe(context=_context()) + finally: + ChildCopy.definition = CHILD_DEFINITION + + +def test_alter_unchanged_definition(schema_indexes, monkeypatch): + """alter() with an unchanged definition runs no statement.""" + connection = Child.connection + before = (Child().describe(context=_context()), _indexes(Child())) + statements = [] + query = connection.query + + def recording_query(sql, *args, **kwargs): + statements.append(sql) + return query(sql, *args, **kwargs) + + monkeypatch.setattr(connection, "query", recording_query) + Child.alter(prompt=False, context=_context()) + monkeypatch.undo() + assert not [s for s in statements if s.lstrip().upper().startswith(("ALTER", "COMMENT", "CREATE", "DROP"))] + assert (Child().describe(context=_context()), _indexes(Child())) == before + + +def test_expression_index_is_skipped(schema_indexes): + """An index with an expression is left out of the heading. + + Neither backend names a column for an expression. Listing only the plain + columns of such an index would describe a different index, so the heading + leaves out any index that contains an expression, on both backends. + """ + child = Child() + connection = child.connection + connection.query(f"CREATE INDEX child_expr ON {child.full_table_name} ((lower(b)))") + connection.query(f"CREATE INDEX child_expr_first ON {child.full_table_name} ((c + 1), a)") + # A unique index that mixes a column and an expression. Its name sorts after + # the plain index on (a) on both backends, so it used to replace that index + # in the heading as a unique index on (a) alone. + connection.query(f"CREATE UNIQUE INDEX zz_mixed_unique ON {child.full_table_name} (a, (lower(b)))") + indexes = _indexes(dj.FreeTable(connection, child.full_table_name)) + assert indexes == EXPECTED_INDEXES + lines = [" ".join(line.split()) for line in child.describe(context=_context()).splitlines()] + assert lines == EXPECTED_DESCRIBE + + +class Ordered(dj.Manual): + # The order of index names differs between backends: MySQL lists INDEX (a, c) + # first and PostgreSQL lists INDEX (a_b) first. On PostgreSQL, index-name + # order also differs from declared order. + definition = """ + ordered_id : int32 + --- + a : int32 + a_b : int32 + c : int32 + index(a, c) + index(a_b) + """ + + +class Unsorted(dj.Manual): + # Declared index order differs from index-name order on both backends: + # index(z) is declared first, and its name sorts after that of index(a). + definition = """ + unsorted_id : int32 + --- + a : int32 + z : int32 + index(z) + index(a) + """ + + +@pytest.mark.parametrize( + "table, expected", + [ + (Ordered, ["INDEX (a, c)", "INDEX (a_b)"]), + (Unsorted, ["INDEX (a)", "INDEX (z)"]), + ], + ids=["ordered", "unsorted"], +) +def test_alter_ignores_index_order(schema_indexes, monkeypatch, table, expected): + """alter() with an unchanged definition does not depend on index order.""" + schema_indexes(table) + connection = table.connection + described = [line for line in table().describe().splitlines() if "INDEX" in line] + assert sorted(" ".join(line.split()) for line in described) == expected + statements = [] + query = connection.query + + def recording_query(sql, *args, **kwargs): + statements.append(sql) + return query(sql, *args, **kwargs) + + monkeypatch.setattr(connection, "query", recording_query) + table.alter(prompt=False) + monkeypatch.undo() + assert not [s for s in statements if s.lstrip().upper().startswith(("ALTER", "COMMENT", "CREATE", "DROP"))] diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index bcfe6a612..1ee9f5835 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -4,6 +4,8 @@ Tests adapter functionality without requiring actual database connections. """ +import re + import pytest from datajoint.adapters import DatabaseAdapter, MySQLAdapter, PostgreSQLAdapter, get_adapter @@ -376,6 +378,14 @@ def test_enum_type_in_use_sql(self, adapter): assert """'"myschema"."enum_abc"'::regtype""" in sql assert "NOT attisdropped" in sql + def test_get_indexes_sql_leaves_out_primary_key(self, adapter): + """Secondary indexes only, one row per key column, expressions kept as NULL columns.""" + sql = adapter.get_indexes_sql("myschema", "mytable") + assert "FROM pg_index " in sql + assert "NOT i.indisprimary" in sql + assert "LEFT JOIN pg_attribute" in sql + assert "k.ord <= i.indnkeyatts" in sql + def test_drop_enum_type_sql(self, adapter): """Test PostgreSQL enum type dropping.""" sql = adapter.drop_enum_type_sql("myschema", "mytable", "status") @@ -450,6 +460,17 @@ def test_adapter_implements_interface(self, backend): assert hasattr(adapter, "parameter_placeholder") assert isinstance(adapter.parameter_placeholder, str) + @pytest.mark.parametrize("backend", ["mysql", "postgresql"]) + def test_indexes_sql_names_heading_columns(self, backend): + """The index query returns the columns Heading reads (#1699).""" + if backend == "postgresql": + pytest.importorskip("psycopg2") + sql = get_adapter(backend).get_indexes_sql("myschema", "mytable") + for column in ("index_name", "column_name", "non_unique", "seq_in_index"): + assert re.search(rf"\bAS\s+{column}\b", sql, re.I), f"query does not return {column}" + assert "'myschema'" in sql + assert "'mytable'" in sql + class TestDDLMethods: """Test DDL generation adapter methods."""