From eef34358bf521be6ec1cf89e2eff16163d8fdb14 Mon Sep 17 00:00:00 2001 From: mayuriphad Date: Tue, 17 Nov 2026 07:40:51 +0530 Subject: [PATCH 1/3] fix(declare): declare JSON-path indexes on PostgreSQL PostgreSQL has no inline INDEX in CREATE TABLE, so declare() re-parses each compiled index into a CREATE INDEX statement. The regex stopped at the first ")" and the column list was split on every comma, so a JSON-path expression was cut into pieces, quoted as identifiers and used in the index name, giving invalid SQL. Split the items on top-level commas, keep parenthesized expressions as they are in create_index_ddl, and derive the index name for an expression from its word characters plus a short hash, capped at 63 characters. Plain column indexes keep their current names. Fixes #1672 Signed-off-by: mayuriphad --- src/datajoint/adapters/base.py | 14 ++++++-- src/datajoint/declare.py | 9 +++-- tests/integration/test_json_index.py | 33 ++++++++++++++++++ tests/unit/test_declare_index.py | 50 ++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 8 deletions(-) create mode 100644 tests/integration/test_json_index.py create mode 100644 tests/unit/test_declare_index.py diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1aa12f52f..ae311ada3 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,18 @@ 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. + digest = hashlib.md5("_".join(columns).encode()).hexdigest()[:8] + col_part = re.sub(r"\W+", "_", col_part).strip("_") + "_" + digest + 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 438bb72b0..c3e59422e 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -615,13 +615,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..dfa2cb92e --- /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:integer) + unique index(item_id, data.name:varchar(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..a4001e870 --- /dev/null +++ b/tests/unit/test_declare_index.py @@ -0,0 +1,50 @@ +"""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")' + + +def test_expression_index_names_are_valid_and_distinct(): + adapter = get_adapter("postgresql") + names = [ + adapter.create_index_ddl('"s"."t"', [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() From 7612756cefd66c4511b43fe86610afcd6fe5c972 Mon Sep 17 00:00:00 2001 From: mayuriphad Date: Tue, 17 Nov 2026 07:46:23 +0530 Subject: [PATCH 2/3] test: use JSON_VALUE types MySQL accepts in the JSON index test MySQL's JSON_VALUE ... RETURNING has no integer or varchar type, so use decimal and char, which both backends accept. Signed-off-by: mayuriphad --- tests/integration/test_json_index.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_json_index.py b/tests/integration/test_json_index.py index dfa2cb92e..7b354e053 100644 --- a/tests/integration/test_json_index.py +++ b/tests/integration/test_json_index.py @@ -25,8 +25,8 @@ class Indexed(dj.Manual): item_id : int32 --- data = null : json - index(data.size:integer) - unique index(item_id, data.name:varchar(20)) + 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)]) From abaf4815aacf8e25ef82d15671adbc1a261d28f8 Mon Sep 17 00:00:00 2001 From: mayuriphad Date: Fri, 20 Nov 2026 21:06:45 +0530 Subject: [PATCH 3/3] fix(declare): keep the hash in long JSON-path index names Cut the readable part of an expression index name before appending the hash, so the hash survives the 63-character limit and two JSON-path indexes on a table with a long name still get distinct names. Signed-off-by: mayuriphad --- src/datajoint/adapters/base.py | 7 +++++-- tests/unit/test_declare_index.py | 5 +++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index ae311ada3..215200892 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -706,9 +706,12 @@ def create_index_ddl( 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("_") + "_" + digest - index_name = f"idx_{table_part}_{col_part}"[:63] + 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/tests/unit/test_declare_index.py b/tests/unit/test_declare_index.py index a4001e870..4789616b4 100644 --- a/tests/unit/test_declare_index.py +++ b/tests/unit/test_declare_index.py @@ -35,10 +35,11 @@ def test_plain_column_index_is_unchanged(index_ddl): assert index_ddl[2] == 'CREATE INDEX "idx_indexed_item_id" ON "s"."indexed" ("item_id")' -def test_expression_index_names_are_valid_and_distinct(): +@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('"s"."t"', [expr]).split('"')[1] + 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)",