diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1aa12f52f..215200892 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -7,6 +7,8 @@ from __future__ import annotations +import hashlib +import re from abc import ABC, abstractmethod from typing import Any @@ -683,7 +685,8 @@ def create_index_ddl( full_table_name : str Fully qualified table name (with quotes). columns : list[str] - Column names to index (unquoted). + Column names to index (unquoted), or parenthesized expressions + such as a JSON path, which are emitted as they are. unique : bool, optional If True, create a unique index. index_name : str, optional @@ -694,13 +697,21 @@ def create_index_ddl( str CREATE INDEX SQL statement. """ - quoted_cols = ", ".join(self.quote_identifier(col) for col in columns) + quoted_cols = ", ".join(col if col.startswith("(") else self.quote_identifier(col) for col in columns) # Generate index name from table and columns if not provided if index_name is None: # Extract table name from full_table_name for index naming _, table_part = self.split_full_table_name(full_table_name) col_part = "_".join(columns)[:30] # Truncate for long column lists - index_name = f"idx_{table_part}_{col_part}" + if any(col.startswith("(") for col in columns): + # Expressions are not valid in an identifier: keep the word + # characters and add a hash so distinct expressions get distinct names. + # Cut before adding the hash, so it survives the 63-character limit. + digest = hashlib.md5("_".join(columns).encode()).hexdigest()[:8] + col_part = re.sub(r"\W+", "_", col_part).strip("_") + index_name = f"idx_{table_part}_{col_part}"[:54] + "_" + digest + else: + index_name = f"idx_{table_part}_{col_part}"[:63] unique_clause = "UNIQUE " if unique else "" return f"CREATE {unique_clause}INDEX {self.quote_identifier(index_name)} ON {full_table_name} ({quoted_cols})" diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 87cef4619..a796e669b 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -818,13 +818,12 @@ def declare( create_table_indexes = [] for idx_def in index_sql: # Parse index definition: "unique index (cols)" or "index (cols)" - idx_match = re.match(r"(unique\s+)?index\s*\(([^)]+)\)", idx_def, re.I) + idx_match = re.match(r"(unique\s+)?index\s*\((.+)\)\s*$", idx_def, re.I) if idx_match: is_unique = idx_match.group(1) is not None - # Extract column names (may be quoted or have expressions) - cols_str = idx_match.group(2) - # Simple split on comma - columns are already quoted - columns = [c.strip().strip('`"') for c in cols_str.split(",")] + # Items are quoted columns or parenthesized expressions (JSON paths). + # Split on top-level commas only, and keep expressions as they are. + columns = [c if c.startswith("(") else c.strip('`"') for c in _parse_index_args(idx_match.group(2))] # Generate CREATE INDEX DDL create_idx_ddl = adapter.create_index_ddl(full_table_name, columns, unique=is_unique) post_ddl.append(create_idx_ddl) diff --git a/tests/integration/test_json_index.py b/tests/integration/test_json_index.py new file mode 100644 index 000000000..7b354e053 --- /dev/null +++ b/tests/integration/test_json_index.py @@ -0,0 +1,33 @@ +"""A JSON-path index declares on both backends (#1672).""" + +import time + +import pytest + +import datajoint as dj + + +@pytest.fixture(scope="function") +def schema_by_backend(connection_by_backend, db_creds_by_backend): + """Create a fresh schema per test, parameterized across backends.""" + backend = db_creds_by_backend["backend"] + test_id = str(int(time.time() * 1000))[-8:] + schema_name = f"djtest_json_index_{backend}_{test_id}"[:64] + schema = dj.Schema(schema_name, connection=connection_by_backend) + yield schema + schema.drop(prompt=False) + + +def test_declare_json_path_index(schema_by_backend): + @schema_by_backend + class Indexed(dj.Manual): + definition = """ + item_id : int32 + --- + data = null : json + index(data.size:decimal(4,1)) + unique index(item_id, data.name:char(20)) + """ + + Indexed.insert([dict(item_id=1, data={"size": 3, "name": "a"}), dict(item_id=2, data=None)]) + assert len(Indexed & "item_id = 1") == 1 diff --git a/tests/unit/test_declare_index.py b/tests/unit/test_declare_index.py new file mode 100644 index 000000000..4789616b4 --- /dev/null +++ b/tests/unit/test_declare_index.py @@ -0,0 +1,51 @@ +"""Index declarations become separate CREATE INDEX statements on PostgreSQL (#1672).""" + +import pytest + +from datajoint.adapters import get_adapter +from datajoint.declare import declare + +DEFINITION = """ +item_id : int32 +--- +data = null : json +index(data.size:integer) +unique index(item_id, data.name:varchar(20)) +index(item_id) +""" + + +@pytest.fixture +def index_ddl(): + *_, post_ddl = declare('"s"."indexed"', DEFINITION, {}, get_adapter("postgresql")) + return [ddl for ddl in post_ddl if "INDEX" in ddl] + + +def test_json_path_index_keeps_the_expression(index_ddl): + assert index_ddl[0].startswith('CREATE INDEX "idx_indexed_jsonb_extract_path_text_') + assert index_ddl[0].endswith(""" ON "s"."indexed" (((jsonb_extract_path_text("data", 'size'))::integer))""") + + +def test_index_mixing_columns_and_json_paths(index_ddl): + assert index_ddl[1].startswith("CREATE UNIQUE INDEX ") + assert index_ddl[1].endswith(""" ON "s"."indexed" ("item_id", ((jsonb_extract_path_text("data", 'name'))::varchar(20)))""") + + +def test_plain_column_index_is_unchanged(index_ddl): + assert index_ddl[2] == 'CREATE INDEX "idx_indexed_item_id" ON "s"."indexed" ("item_id")' + + +@pytest.mark.parametrize("table", ["t", "_ephys_recording_probe_insertion"]) +def test_expression_index_names_are_valid_and_distinct(table): + adapter = get_adapter("postgresql") + names = [ + adapter.create_index_ddl(f'"s"."{table}"', [expr]).split('"')[1] + for expr in ( + "((jsonb_extract_path_text(\"data\", 'a'))::integer)", + "((jsonb_extract_path_text(\"data\", 'b'))::integer)", + ) + ] + assert names[0] != names[1] + for name in names: + assert len(name) <= 63 + assert name.replace("_", "").isalnum()